How to convert from string to a number, and vice-versa in C++?
DEAR All
I'm new to the C++, so maybe someone can say 开发者_高级运维what the proper way to write a function that gets a string char (represents number) and converts it to the integer number.
For example : input : Sixty five, output: 65.
Maybe it should use by cin.getline() ?
Well, vice-versa is little bit simlper...
Thanks for advance. Igal
Here's an illustration of a key part of a solution:
const char* digits[] = {"zero", "one", "two", ...};
const char* tens[] = {"ten", "twenty", "thirty", ...};
// Loop to compare input text tokens against above
...
The idea is to simplify conversion from text to digits by using the array index for the corresponding text token as the means for converting to the digit, adjusting for any array index start differences.
Use either the strcmp
C function or the ==
C++ string comparison operator depending on what datatypes you have for the input text tokens.
This is how to do it in Ruby (handles fractions as well):
http://github.com/jduff/numerizer/blob/master/lib/numerizer.rb
It shouldn't be too hard to translate to C++
精彩评论