The goal of this program is to convert from number to English text. I am a beginner C++ programmer so please don't give complex explanations. Maybe someone can give me another method to approach the algorithim.
// Example program
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
void less_hundred(int number);
void onsy(int number);
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
if (number < 100)
{
less_hundred(number);
}
}
void ones(int number)
{
string onsy;
int j = number % 10;
if (j == 1)
{
onsy = "one";
}
cout << onsy;
}
void less_hundred(int number)
{
string ty;
int i = number / 10;
if (i == 2)
{
ty = "twenty";
}
if (i == 3)
{
ty = "thirty";
}
if (i == 4)
{
ty = "fourty";
}
if (i == 5)
{
ty = "fifty";
}
if (i == 6)
{
ty = "sixty";
}
if (i == 7)
{
ty = "seventy";
}
if (i == 8)
{
ty = "eighty";
}
if (i == 9)
{
ty = "ninty";
}
cout << ty << ' ' << ones(number);
}
Well here's some hints:
Are you aware of the modulus ( % ) operator and integer division?
Basically, 238 % 10 = 8 because 8 is the remainder when you divide 238 by 10.
and, 238 / 10 = 23.
You can use these two operations to get the first and last digits of any number.
Then, you can do more manipulation to get two separate numbers as the final result.
_________________________
Another way to do it is to use std::stringstreams. They can convert strings into numbers and back using the << and >> operators. They can be really convenient and powerful.
Here's a small example you can work from:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <sstream> // std::stringstream
#include <string> // std::string
int main()
{
usingnamespace std;
int x = 5;
stringstream ss;
ss << x; // store x into ss
string my_string = ss.str() + " as a string!";
cout << my_string << endl;
int x2;
ss >> x2; // will fail if the current stringstream can't be represented as an integer.
cout << x2 << " as a number again!" << endl;
}