How to get std :: getline to tell me when it got to the end of the string stream?

Assuming stringstream contains James is 4 , I can write something like getline (stream, stringjames, ' ') to get single words, but is there any way to find out that I got to the end of the line?

Bonus question! Case 1: James is 4 Case 2: James is 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?

+4
source share
2 answers

You check the return value to see if it evaluates to true or false:

 if (getline(stream, stringjames, ' ')) // do stuff else // fail 

Regarding the "bonus question", you can also do the same when fetching int and things from threads. The returned value of operator>> will be evaluated to true if the reading was successful, and false if there was an error (for example, there were letters instead of letters):

 int intval; if (stream >> intval) // int read, process else if (stream.eof()) // end-of-stream reached else // int failed to read but there is still stuff left in the stream 
+6
source

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.

+1
source

Source: https://habr.com/ru/post/1436047/


All Articles