Member Avatar for 7h3.doctorat3

Hi i'm new to using c++ and i would like to ask if you could help me out. I have to somehow get a working c++ program that will allow me to convert any one, two or three digit positive integer into words using string/array method. Say, 111 will be converted into one hundred and eleven. I would greatly appreciate it if you could help me out.

Member Avatar for daviddoria

I would put the numerical representation of the number into an std::string. From here you can access each digit separately:

std::string number = "123"; std::cout << number[0]; //outputs '1'

You would then have to have a giant switch statement to convert a '1' to "one", etc.

Hope this helps,

Dave

Member Avatar for iamthwee

Google it. I bet the generic algorithm for this has been done many times before.

If you're only using three digits max it shouldn't be too hard.

For example the following looks like a useful template, written in java though.

http://www.rgagnon.com/javadetails/java-0426.html

#include <iostream> #include <string> #include <climits> class Foo { public: std::string bar(int number) { std::string tensNames[] = { "", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety" }; std::string numNames[] = { "", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" }; std::string soFar; if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) return soFar + "\n"; return numNames[number] + " hundred" + soFar + "\n"; } }; int main() { Foo bar; std::cout << bar.bar(125); std::cout << bar.bar(9); std::cout << bar.bar(1); std::cout << bar.bar(200); std::cout << bar.bar(999); std::cin.get(); }
Member Avatar for mrnutty

If its only 1-3 length, then just hard code it like so :

int toInt(const string& str){ int result = 0; switch(str.length()){ case 1: result = str[0] - '0'; break; case 2: result = (str[0]-'0')*10 + (str[1] - '0'); break; case 3: result = (str[0]-'0')*100 + (str[1] - '0')*10 + (str[2] - '0'); break; default: /* not supported */ break; } return result; }
Member Avatar for daviddoria

firstPerson - what is this supposed to do? Convert a string to an int? Shouldn't he just use a std::stringstream?

Member Avatar for mrnutty

firstPerson - what is this supposed to do? Convert a string to an int? Shouldn't he just use a std::stringstream?

sorry misread his post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.