Home c++ ISTRINGSTREAM C++ behavior and its alternative

ISTRINGSTREAM C++ behavior and its alternative

Author

Date

Category

There is a function hexstr_to_str Reading from Memory (not file, not CIN) Text flow “01 03 10 FA”, and written to STD :: String containing \ x01 \ x03 \ x10 \ xfa. The problem with reading from the stream of integers is that after reading the last number set flag in the flow of Failbit . Is there an alternative to iStringStream, or after reading each number from the thread, it is necessary to check the end of the line, for example, through peek ()? Are there any decisions easier?

# include & lt; iostream & gt;
#Include & lt; sstream & gt;
SSIZE_T HEXSTR_TO_STR (STD :: STRING & AMP; DESTINATION, STD :: ISTRINGSTREAM & AMP; STREAM_SOURCE)
{
  std :: ios :: fmtflags
       old_flags = stream_source.setf (std :: ios :: hex, std :: ios :: basefield);
  Size_t count = 0;
  int symbol = -1;
  destination.clear ();
  While (Stream_Source & GT; & GT; Symbol) // Adding & AMP; & AMP; ! stream_source.eof () Results did not give.
  {
    DESTINATION + = SYMBOL;
    ++ Count;
  }
  stream_source.setf (old_flags);
  STD :: COUT & LT; & LT; (stream_source.rdstate () & amp; (stream_source.failbit | stream_source.badbit)) & lt; & lt; "\ n";
  Return! (stream_source.rdstate () & amp; (stream_source.failbit | stream_source.badbit))? Count: -Count;
}
INT MAIN ()
{
  STD :: STRING HB_STR;
  // STD :: COUT & LT; & LT; Hexstr_TO_STR (Hello_str, STD :: ISTRINGSTREAM (CSTR_HEX_HELLO));
  Hexstr_TO_STR (HB_STR, STD :: ISTRINGSTREAM ("10 20 AF 30"));
  Return 0;
}

Answer 1

Why do failbook Do you consider a problem?

Forget about it, this is normal behavior at the end of the line.

Check the eof – if the end of the line is achieved, then the analysis of the string was successful. If not achieved – it means there was a mistake:

return stream_source.eof ()? Count: -Count;

Answer 2

just in case (entertained)

using namespace STD;
String Get_xstr (String Str, Long * Errpos) {
 If (ERRPOS)
  * ERRPOS = -1;
 ISTRINGSTREAM ISTR (STR);
 OstringStream Ostr;
 Long X, Curpos;
 IStr.setf (STD :: IOS :: Hex, Std :: iOS :: Basefield);
 ostr.setf (std :: ios :: hex, std :: ios :: basefield);
 While (ISTR & GT; & GT; X) {
  Curpos = Istr.tellg ();
  Ostr & lt; & lt; "\\ x" & lt; & lt; x;
 }
 if (! istr.eof () & amp; & amp; ERRPOS)
  * ERRPOS = CURPOS;
 Return Ostr.str ();
}

Please note the possible error position in the line you have to take in the cycle, since the behavior of .tellg () Similar to nonsense with FAILBIT .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions