You can directly inspect a stringstream
's contents. That may be a clearer approach than extracting and rolling back, as you aren't guaranteed your stringstream
s condition after extraction. For example, if your string only contained one word, extracting it would have set the ios_base::iostate::eofbit
flag.
You could accomplish inspecting the stringstream
's contents like this:
if(sstr.str().compare(0, identifier.length(), identifier) == 0) {
sstr.ignore(identifier.length());
// process the the rest of the string stream using method 1
} else {
// process the stream using method 2
}
One risk this takes on is, if you were depending upon the stringstream
's extraction operator to eliminate leading white-space you'll need to purge before doing the compare
. This can be done by before your if
-block with the command sstr >> skipws;
.
While I do consider this method safer, it should be noted that if you are dependent upon leading white-space being in sstr
for "method 2" then you should use one of the other answers (but you should also reconsider your use of stringstream
since all the extraction operators first eat white-space.)