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;
}
While your question states that you wish to
using
stringstream
, it's worth noting that you don't needstringstream
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:And then perform the conversions.
Why use this? Think about happens if you use a stringstream object on something like the following:
which will simply be parsed and stored as a regular string.
You could make of the validity of stringstream to int conversion:
Exceptions should not scary you.