c++ - istream_iterator behaviour on 0x9-0xD -


i have written small test file make question clear :

#include <iostream> #include <iterator> #include <algorithm> #include <cstdio> #include <sstream>  void printchar(const char c) {          std::string s(&c);         std::istringstream iss(s);          std::ostringstream oss;          std::copy(std::istream_iterator<char>(iss),                   std::istream_iterator<char>(), // reads till end                    std::ostream_iterator<char>(oss));          std::string output = oss.str();         printf("%#x - %#x\n", c, output.c_str()[0]); }  int main (const int argc, const char** argv) {          (char = 0; < 0x20; ++i) {                 printchar(i);         }         return 0; } 

now, expected output going

 0 - 0  0x1 - 0x1  0x2 - 0x2  ...  0x1e - 0x1e  0x1f - 0x1f 

however, following output 0x9-0xd :

0x8 - 0x8 0x9 - 0x7f 0xa - 0x7f 0xb - 0x7f 0xc - 0x7f 0xd - 0x7f 0xe - 0xe 

can explain why result ?

if fix issue mentioned (with std::string constructor) ,

0x8 - 0x8 0x9 - 0 0xa - 0 0xb - 0 0xc - 0 0xd - 0 0xe - 0xe 

this still undefined behaviour because dereferencing output when empty. reason empty streams ignore whitespace - considered delimiters.

changing printf to

printf("%#x - %#x\n", c, !output.empty() ? output.c_str()[0] : -1); 

gives

0x8 - 0x8 0x9 - 0xffffffff 0xa - 0xffffffff 0xb - 0xffffffff 0xc - 0xffffffff 0xd - 0xffffffff 0xe - 0xe 

Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -