Search code examples
c++stringstream

C++ Extract int from string using stringstream


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 string being checked is an int. I've looked up how to do this, but most seem to throw exceptions - I need it to keep going until it hits an int.

Later I will adjust to account for a string that doesn't contain any ints, but for now any ideas on how to get past this part?

(For now, I'm just inputting a test string rather than use getline each time.)

int main() {

    std::stringstream ss;
    std::string input = "a b c 4 e";

    ss.str("");
    ss.clear();

    ss << input;

    int found;
    std::string temp = "";

    while(!ss.eof()) {
            ss >> temp;
            // if temp not an int
                    ss >> temp; // keep iterating
            } else {
                    found = std::stoi(temp); // convert to int
            }
    }

    std::cout << found << std::endl;

    return 0;
}

Solution

  • You could make use 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;
    }