The exercise asks for a code which can convert the user input of the numbers 0-9 either as an integer or string to a string or integer respectively i.e. if0 is entered "zero" will be outputted and vice versa.
string number;
cout << "Let's convert strings to numbers."
<< "Enter value/string of 0-9";
while (number!= "exit")
{
cin >> number;
for (int i=0; i < digits.size(); i++)
{
if (number == digits[i]) cout << i << endl;
}
if (number == "0") cout << digits[0] << endl;
else if (number == "1") cout << digits[1] << endl;
else if (number == "2") cout << digits[2] << endl;
else if (number == "3") cout << digits[3] << endl;
else if (number == "4") cout << digits[4] << endl;
else if (number == "5") cout << digits[5] << endl;
else if (number == "6") cout << digits[6] << endl;
else if (number == "7") cout << digits[7] << endl;
else if (number == "8") cout << digits[8] << endl;
else if (number == "9") cout << digits[9] << endl;
}
digits is a vector class which stores the strings "zero", "one" etc.
This code works fine but I don’t like the long chain of if/else if statements but I can’t figure out a way to convert the integers to strings. Can someone help me make this more efficient? Thanks!
you can use that
if number == "0"thennumber[0] == '0'which ischar.e.i instead if/else statements:
stringis basically an array of characters,std::stringis an array of characters of typechar.For instance these are two legimate ways to declare and initialize strings in c or c++
Char value is technically integer (or rather byte) that stores the character code in some encoding (usually ASCII).
For instance the character code of ‘0’ is 48, that of ‘1’ is 49, ‘2’ is 50. And we use this, because we know that