I am writing this program, in which we need to convert the input from the user from digits into words. I've written the whole program. The only error I am facing is that when I write e.g. 4200, the zeros aren't appearing. I am a beginner at C .
while (num > 0)
{
rem = num % 10;
sum = sum * 10 rem;
num = num / 10;
}
num = sum;
while (num > 0)
{
rem = num % 10;
switch (rem)
{
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;
Please help me out. How can I print the zeros too?
CodePudding user response:
Your solution is not optimal. So, I have written a new solution.
Solution
int num;
cin >> num;
vector<string> v;
while (num > 0) {
switch (num % 10) {
case 1:
v.push_back("One");
break;
case 2:
v.push_back("Two");
break;
case 3:
v.push_back("Three");
break;
case 4:
v.push_back("Four");
break;
case 5:
v.push_back("Five");
break;
case 6:
v.push_back("Six");
break;
case 7:
v.push_back("Seven");
break;
case 8:
v.push_back("Eight");
break;
case 9:
v.push_back("Nine");
break;
case 0:
v.push_back("Zero");
break;
}
num /= 10;
}
reverse(v.begin(), v.end());
for (auto a: v) cout << a << " ";
You also can use map
instead of switch
.
If you get any errors try to write #include <vector>
.
Very simple solution
int num;
cin >> num;
string s;
while (num > 0) {
switch (num % 10) {
case 1:
s = "One " s;
break;
case 2:
s = "Two " s;
break;
case 3:
s = "Three " s;
break;
case 4:
s = "Four " s;
break;
case 5:
s = "Five " s;
break;
case 6:
s = "Six " s;
break;
case 7:
s = "Seven " s;
break;
case 8:
s = "Eight " s;
break;
case 9:
s = "Nine " s;
break;
case 0:
s = "Zero " s;
break;
}
num /= 10;
}
cout << s;
CodePudding user response:
If your goal is simply to convert digits as-is into words, there is a much simpler approach:
string input;
cin >> input;
for (char ch : input)
{
switch (ch)
{
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;
}
}