C++ Extract int from string using stringstream

后端 未结 3 1490
無奈伤痛
無奈伤痛 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;
    

提交回复
热议问题