Search code examples
c++stringintegeratoiistringstream

How To Read Multiple Integers from a String C++


I'm trying to understand how can I convert multiple integers from a string. I have tried to use atoi(), stoi() and istringstream() and they all do the same thing. I can't get more than one integer.

For example, if the string is "Chocolate and Milk 250 pounds and 2 oz or 1.5 coins." All of the above functions will not work. It won't take the whole string. If I leave only a single number then it will work. I want to be able to read the whole string and get all of the integers only (not float).

I am using a while(getline()) for the string. Then try to get it into string.

Although, if I could only return the total amount of integers in the string that would be better. Either way, I'm trying to learn both ways. In this case, the output would be "2", since there are only two int.


Solution

  • One way is to split the string using as delimiter and using stoi on individual strings to check if they are integers.

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main(){
        std::string s = "Chocolate and Milk 250 pounds and 2 oz or 1.5 coins.";
        int count = 0;
        std::istringstream iss(s);
        std::string token;
        while(getline(iss,token,' ')){
            if(std::isdigit(token[0]) &&stoi(token) && token.find('.')==std::string::npos){
                count++;
            }
        }
    
        std::cout<<count<<std::endl;
    }
    

    Note that more complex checks can be done on strings if stoi succeeds, but the input is not a valid integer. You can have a helper function which checks if all the characters are digits or not by using isdigit etc.