Istream extract operator: how to detect syntax syndrome?

How to determine if istream extraction was able to be extracted this way?

string s("x"); stringstream ss(s); int i; ss >> std::ios::hex >> i; 

EDIT. Although the title of the question covers this, I forgot to mention in the body: I โ€‹โ€‹really want to determine if a failure occurred due to poor formatting, i.e. parsing or due to any other IO related issue, in order to provide the correct feedback communication (misconception ("x") or something else).

+4
source share
4 answers

First of all: thanks for the helpful answers. However, after some research (cfr. Cppreference ) and verification, it seems that the only way to check only parsing is to check ios::failbit , as in

 const bool parsing_failed = (ss >> ios::hex >> i).rdstate() & ios::failbit ; 

Although both suggested by istream::operator! and istream::operator bool mingle failbit and badbit (cfr here and there on cplusplusreference).

0
source
 if(! (ss >> std::ios::hex >> i) ) { std::cerr << "stream extraction failed!" << std::endl; } 

It is just so easy.

ETA: Here is an example of how this test interacts with the end of the stream.

 int i; std::stringstream sstr("1 2 3 4"); while(sstr >> i) { std::cout << i << std::endl; if(sstr.eof()) { std::cout << "eof" << std::endl; } } 

will print 1
2
3
4
Wf

If you were to check sstr.eof() or sstr.good() in a while loop condition, 4 will not be printed.

+9
source

Failure to extract the value will set the "fail" bit of the stream, which can be detected using if (ss.fail()) or simply if (!ss) . Equivalently, you can check the result of the >> operation, as this returns a link to the stream.

They will also detect other errors that set the โ€œbadโ€ bit; you can distinguish them from ss.bad() .

If you want to continue reading from the stream, you need to clear the status flags ( ss.clear() ).

+4
source

Errors during extraction are signaled by internal flags. You can check them using the member function good() . See also here: http://www.cplusplus.com/reference/iostream/stringstream

Or simply using the if() construct, as suggested above. This works because of the bool cast operator of stream classes

0
source

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


All Articles