Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count only integers in a string

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?

like image 613
banksters Avatar asked Feb 09 '23 00:02

banksters


2 Answers

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++;
    }
}
like image 126
molbdnilo Avatar answered Feb 11 '23 15:02

molbdnilo


The operator>> returns the stream which has a conversion to bool indicating whether any error flags are set; that's what is used in your while loop. If the character sequence at the read position in the stream is not an int, the fail bit is set and the stream converts to false in the loop, ending the program.

You probably want to check that bit in the loop. If it is the fail bit (and not eof), clear it, read away the string that's between the ints, and continue in the loop.

You were not very exact with your specification; the algorithm described above would return 1 for the string "123 abx2". If you want to return 2 or 4 here you must inspect the data at the single character level.

like image 22
Peter - Reinstate Monica Avatar answered Feb 11 '23 15:02

Peter - Reinstate Monica