Erik Kastas Carney Erik Kastas Carney - 4 years ago 108
C++ Question

C++ integer digits printed out in string?

So the code I'm working on (for school) is suppose to take a user given integer and print it out in a string (example input: 154 | output: One Five Four).

Currently I ALMOST have it figured out, except it is backwards! Need to figure how to have it printed the right way (mine would print out Four Five One).

#include <iostream>
#include <string>

using namespace std;

void toString(int x) {
while (x > 0)
{
int digit = x % 10;
x /= 10;
switch (digit) {
case 1:
cout << "One ";
break;
case 2:
cout << "Two ";
break;
case 3:
cout << "Three ";
break;
case 4:
cout << "Four ";
break;
case 5:
cout << "Five ";
break;
case 6:
cout << "Six ";
break;
case 7:
cout << "Seven ";
break;
case 8:
cout << "Eight ";
break;
case 9:
cout << "Nine ";
break;
case 0:
cout << "Zero ";
break;
}
}
}

int main()
{
int num;

cout << "Please enter a positive number" << endl;
cin >> num;

while (num > 0)
{
toString(num);
cout << "\nPlease enter a positive number" << endl;
cin >> num;
}

cout << "You entered a number less than or equal to zero"
<< endl << "the program was terminated" << endl;

system("pause");
return 0;
}

Answer Source

There are basically three ways to solve your problem:

  1. Instead of printing the words, put them in a string and then reverse the words in the string.

  2. Reverse the number before the loop.

  3. Start at the other end of the number, by counting the number of digits and (in the example of 154) start with the hundreds, then do the tens, and finally the ones.

The easiest is a variant of the first alternative, where instead of creating a string containing the words and then reversing the words, you put the words into a container (e.g. std::vector) and then either reverse the container or iterate from the back to the front.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download