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);
}
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.
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.