Suppose the stringstream contains James is 4, I can write something like getline (stream, stringjames, '') to get individual words, but is there any way to find out that I got to the end of the line?
As a rule, the easiest way is to read the variable std::string - by default it is assumed that it is limited to a space:
std::string word; while (some_stream >> word) { // first iteration "James", then "is", then "4", then breaks from while... }
Bonus question! Case 1: James 4 Case 2: James Four
If I were repeating words in a string stream and I expected to get int val from 4, but instead I got a string, what would be the best way to check this?
It is best to first read it into a string and then check if you can convert this string to a number. You can try strtoi etc. - they help indicate whether the entire value is a legal number so that you can detect and reject the values, for example, say β4qβ.
An alternative is to try to do the streaming conversion to an integral type first, and only if it fails reset the error flags in the stream and get a string instead. I canβt remember if you need to move the stream so that you can read the string variable, but you could write a couple of test cases and turn them off.
Alternatively, you can use regular expressions and subexpressions to parse your input: more useful as the expression becomes more complex.
source share