15.6. Parsing numbers¶
The next task is to convert the numbers in the file from strings to
integers. When people write large numbers, they often use commas to
group the digits, as in 1,750. Most of the time when computers write
large numbers, they don’t include commas, and the built-in functions for
reading numbers usually can’t handle them. That makes the conversion a
little more difficult, but it also provides an opportunity to write a
comma-stripping function, so that’s ok. Once we get rid of the commas,
we can use the library function atoi
to convert to integer. atoi
is defined in the header file cstdlib
.
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.
#include <iostream>
using namespace std;
int convertToInt (const string& s)
{
string digitString = "";
for (size_t 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.
Try the function out for yourself! As you can see, this function can also be used to parse phone numbers!
- takes the absolute value of a number
- Incorrect! Go back and read for the answer.
- converts a double to an int
- Incorrect! Go back and read for the answer.
- converts a string to an int
- Correct! This is very helpful when we read numbers from a file (where they are strings).
- converts an int to a string
- Incorrect! Go back and read for the answer.
Q-2: What does the atoi()
function do?
- 2020
- Correct! This one is quite simple.
- ab,jkl2!!moo0?huh2mth0haha.
- Correct! This long, confusing string will clean up nicely!
- 2,00!!!!!!!!2
- Incorrect!
- 2OOO020OOOOO
- Correct! You have to look closely to see that some of these are 0's!
- we2love0parsing2numbersO!
- Incorrect! Although we do love parsing numbers, this is incorrect.
Q-3: Which of the following strings will return “2020” when passed into convertToInt()
?
Create the replace_with() function that takes a string “str”, a character to get rid of “olc_char”, and a character to replace it with “new_char”. It should return a new string that has replaces any occurances of old_char with new_char.