This function below simply takes a string that is being filled with 64 bits integer, and each value is separated by a delimiter character, which will be put into the vector.
vector<unsigned long long int> getAllNumbersInString(string line, char delim){
vector<unsigned long long int> v;
string word;
stringstream stream(line);
unsigned long long int num;
while(getline(stream, word, delim))
num = atol(word.c_str());
v.push_back(num);
}
return v;
}
This function works fine when, for instance, we have ‘,’ as delimiter, however, the delimiter will fail if the data in the string variable “line” is like this:
432 12332 2234 12399
While it seems the data uses white space as a delimiter, with the code above, the whole code will fail logically. For instance, the white space between white space is undefined and atol will return 0, and putting these zeros into the vector.
In order to better guard against these anomolies, what are the measures I should put into this code?
Is there some reason you can’t/won’t just use something like this?:
or just:
If you have to deal with delimiters other than whitespace, you can create a ctype facet to specify what else should be treated as delimiters.