I wrote a program that, when you enter a number in the form of a name, will produce the number itself, and vice versa. For example, when you enter "one" program displays "1" , when you enter "1" it gives "one" , etc. to nine.

 int main() { vector<string> numb = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; vector<int> val = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (string num; cin >> num;) { bool found = false; int b = 0; for (int i = 0; i < numb.size(); ++i) { if (num == numb[i]) { found = true; b = i; break; } } if (found) cout << val[b] << endl; else for (int a = 0; cin >> a;) { cout << numb[a] << endl; break; } } return 0; } 

And with alphabetic input and numerical output, everything is in order, but with the input of a number and the output of "letters" it works through time. Ie I enter the "1" and nothing happens - no error, or anything else. Then I enter "1" again, and then the program returns "one" . Help me understand what is wrong, please.

    1 answer 1

    You have already read the number, it did not coincide with the lines. And you try to read it again ...

    Replace the else block with the following:

      else { int a = stoi(num); cout << numb[a] << endl; } 

    And note that you do not handle errors at all! What if I enter "один" or 845? Think about it ...

    • Thank you. Yes, I have not yet thought about errors, because I can make it work like this: D And could you explain in more detail why I should write the string int a = stoi (num); ? - niki4iko
    • Because num you have a string , and you need a number . - Harry