i want to numbers in the text entered by the user are converted into text and printed on the screen. Example:
cin>> My School Number is 5674
and i want to "my school number is five six seven four" output like this. I make only Convert to number to text but i cant put together text and numbers please help me
`
#include <iostream>
using namespace std;
void NumbertoCharacter(int n)
{
int rev = 0, r = 0;
while (n > 0) {
r = n % 10;
rev = rev * 10 + r;
n = n / 10;
}
while (rev > 0) {
r = rev % 10;
switch (r) {
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;
default:
cout << "invalid ";
break;
}
rev = rev / 10;
}
}
int main()
{
int n;
cin >> n;
NumbertoCharacter(n);
return 0;
}
`
>Solution :
Here is a solution.
The key line is the int charToInt = a - '0';. Here is a link to more details on that technique.
If the value returned (charToInt) is between 0 and 9, then the character is a valid integer and can be converted. If not, then just print the original character.
I also changed cin to getline (documentation here) so that your input can accept multiple words.
void NumbertoCharacter(string n)
{
for (auto a : n) {
int charToInt = a - '0';
if (charToInt >= 0 && charToInt <= 9) {
switch (charToInt) {
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;
default:
cout << "invalid ";
break;
}
}
else {
cout << a;
}
}
cout << endl;
}
int main(int argc, char** argv) {
string n;
getline(cin, n);
NumbertoCharacter(n);
return 0;
}