0x9-0xD上的istream_iterator行为

时间:2017-07-25 13:33:35

标签: c++ stringstream istream-iterator

我写了一个小测试文件,以明确问题:

#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 the 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) {

        for (char i = 0; i < 0x20; ++i) {
                printChar(i);
        }
        return 0;
}

现在,预期的输出将是

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

但是,我得到0x9-0xD的以下输出:

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

有谁可以解释为什么我得到这个结果?

2 个答案:

答案 0 :(得分:2)

构造字符串s时,您有undefined behavior。您没有提供&c提供的“字符串”的长度,导致构造函数在搜索字符串终止符时越界

您需要在此处明确提供长度:

std::string s(&c, 1);

答案 1 :(得分:2)

如果您修复了已经提到的问题(使用std :: string构造函数),您将获得

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

这仍然是未定义的行为,因为当它为空时您将取消引用output。它是空的原因是流忽略空格 - 它们被认为是分隔符。

将printf更改为

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

给出

0x8 - 0x8
0x9 - 0xffffffff
0xa - 0xffffffff
0xb - 0xffffffff
0xc - 0xffffffff
0xd - 0xffffffff
0xe - 0xe
相关问题