I have this small piece of code that I'm trying to work on that takes in a string, and adds one to a counter for every number in the string separated by a space. However, if it runs into something that is not an integer, it immediately stops the counter which isn't what I want it to do.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int counter;
int main()
{
cout << "Please input string: ";
string input;
getline(cin, input);
istringstream ss(input);
int num;
while(ss >> num)
{
counter++;
}
cout << "Amount of integers in string: " << counter << endl;
}
For example, if I input the string 3 4 5
, it will correctly return 3 integers in the string, but if I input something like 3 4 x 6 t 8
, it will say I only had two integers in the string.
How do I fix this?
ss >> num
will put the stream in an error state as soon as it encounters a non-integer, which will make while (ss >> num)
terminate.
Like many other problems, this can be solved by introducing a level of indirection of some sort.
In this case, you can use indirection through a second stream:
istringstream ss(input);
string word;
while (ss >> word)
{
istringstream maybenumber(word);
int number = 0;
if (maybenumber >> number)
{
counter++;
}
}