The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home File Input/Output and pmatrices Parsing Numbers | ||
Parsing Numbers
To get rid of the commas, one option is to traverse the string and check whether each character is a digit. If so, we add it to the result string. At the end of the loop, the result string contains all the digits from the original string, in order. int convertToInt (const pstring& s){ pstring digitString = ""; for (int i=0; i<s.length(); i++) { if (isdigit (s[i])) { digitString += s[i]; } } return atoi (digitString.c_str()); } The variable digitString is an example of an accumulator. It is similar to the counter we saw in Section 7.9, except that instead of getting incremented, it gets accumulates one new character at a time, using string concatentation. The expression digitString += s[i];is equivalent to digitString = digitString + s[i];Both statements add a single character onto the end of the existing string. Since atoi takes a C string as a parameter, we have to convert digitString to a C string before passing it as an argument.
|
||
Home File Input/Output and pmatrices Parsing Numbers |