Cześć, niedawno zacząłem się uczyć C++. Idzie mi strasznie opornie, ale postanowiłem że mimo wszystko się z tym uporam.
Jednym z ćwiczeń które miałem zrobić to kalkulator z obsługą liczb pisanych słownie np. "jeden + "dwa".
Po kilku minutach powstało to coś. Mój problem w tym, że kod jest brzydki i nieczytelny. Proszę was więc o kilka wskazówek na przyszłość, może są na to co zrobiłem szybsze rozwiązania.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int transmute(string x){
vector<string> v(10);
v[0] = "zero";
v[1] = "jeden"; //nie wiem czy da sie to zrobic "ładniejszym" sposobem
v[2] = "dwa";
v[3] = "trzy";
v[4] = "cztery";
v[5] = "piec";
v[6] = "szesc";
v[7] = "siedem";
v[8] = "osiem";
v[9] = "dziewiec";
if (x != "0" && x != "1" && x != "2" && x != "3" && x != "4" && x != "5" && x != "6" && x != "7" && x != "8" && x != "9"){//jesli x nie jest liczba
for (unsigned int i = 0; i < v.size(); i++)//to szukaj w wektorze
if (x == v[i])//jak znajdziesz
return i;//to wypluj numer.
}
else if (x != "0" && x != "1" && x != "2" && x != "3" && x != "4" && x != "5" && x != "6" && x != "7" && x != "8" && x != "9" && x != v[0] && x != v[1] && x != v[2] && x != v[3] && x != v[4] && x != v[5] && x != v[6] && x != v[7] && x != v[8] && x != v[9])
return -1;//nie mialem bladego pojecia jak to inaczej zrobic, az mnie bolalo ze musze pisac takie cos.
else if (x == "0")
return 0;
else if (x == "1")
return 1;
else if (x == "2")
return 2;
else if (x == "3")//tu tak samo, jestem pewien ze jest lepszy sposob
return 3;
else if (x == "4")
return 4;
else if (x == "5")
return 5;
else if (x == "6")
return 6;
else if (x == "7")
return 7;
else if (x == "8")
return 8;
else if (x == "9")
return 9;
}
int main() {
char oper;
string liczba1;
string y;
int arg1 = 0;
int arg2 = 0;
cout << "Podaj dzialanie z liczbami od 0 do 9\n";
while(cin>>liczba1 && cin>>oper && cin>>y) {
arg1 = transmute(liczba1);//transmute przerabia liczby pisane slownie na normalne
arg2 = transmute(y);
if (oper != '+' && oper!= '-' && oper!= '*' && oper != '/'){
cout << "Nieprawidlowy znak: " << oper << "\n";//jesli znak jest zly
continue;
}
else if (arg1 > 9 || arg1 < 0 || arg2 > 9 || arg1 < 0){
cout << "Jedna z liczb ktore podales jest za duza!\n";//jesli jeden z argumentow jest za duzy. dodane z powodu obslugi slownych liczb.
continue;
}
else if (oper == '+')
cout << arg1 << oper << arg2 << "=" << arg1+arg2 << "\n";
else if (oper == '-')
cout << arg1 << oper << arg2 << "=" << arg1-arg2 << "\n";
else if (oper == '*')
cout << arg1 << oper << arg2 << "=" << arg1*arg2 << "\n";
else if (oper == '/'){
if (arg2 == 0)
cout << "Niedozwolone dzialanie : Dzielenie przez 0\n";
else
cout << arg1 << oper << arg2 << "=" << arg1/arg2 << "\n";
}
}
return 0;
}
Pozdrawiam :)