C++ Extract int from string using stringstream

后端 未结 3 1491
無奈伤痛
無奈伤痛 2020-12-10 09:50

I am trying to write a short line that gets a string using getline and checks it for an int using stringstream. I am having trouble with how to check if the part of the stri

相关标签:
3条回答
  • 2020-12-10 10:14

    Exceptions should not scary you.

    int foundVal;
    found = false;
    
    while(!found || !ss.eof()) {
        try
        {
           foundVal = std::stoi(temp);  //try to convert
           found = true;
        }
        catch(std::exception& e)
        {
            ss >> temp; // keep iterating
        }
    }
    
    if(found)
        std::cout << foundVal << std::endl;
    else
        std::cout << "No integers found" << std::endl;
    
    0 讨论(0)
  • 2020-12-10 10:18

    You could make of the validity of stringstream to int conversion:

    int main() {
    
    std::stringstream ss;
    std::string input = "a b c 4 e";
    ss << input;
    int found;
    std::string temp;
    
    while(std::getline(ss, temp,' ')) {
        if(std::stringstream(temp)>>found)
        {
            std::cout<<found<<std::endl;
        }
    }
    return 0;
    }
    
    0 讨论(0)
  • 2020-12-10 10:29

    While your question states that you wish to

    get a string using getline and checks it for an int

    using stringstream, it's worth noting that you don't need stringstream at all. You only use stringstreams when you want to do parsing and rudimentary string conversions.

    A better idea would be to use functions defined by std::string to find if the string contains numbers as follows:

    #include <iostream>
    #include <string>
    
    int main() {
        std::string input = "a b c 4 e 9879";//I added some more extra characters to prove my point.
        std::string numbers = "0123456789";
        std::size_t found = input.find_first_of(numbers.c_str());
    
        while (found != std::string::npos) {
            std::cout << found << std::endl;
            found = input.find_first_of(numbers.c_str(), found+1);
        }
    
        return 0;
    }
    

    And then perform the conversions.

    Why use this? Think about happens if you use a stringstream object on something like the following:

    "abcdef123ghij"

    which will simply be parsed and stored as a regular string.

    0 讨论(0)
提交回复
热议问题