代码之家  ›  专栏  ›  技术社区  ›  user180574

C++:使用sstream进行序列化

  •  1
  • user180574  · 技术社区  · 2 年前

    我正在测试下面的一个序列化代码,它因几个数字而失败。知道吗?

    #include <iostream>
    #include <sstream>
    
    
    int main()
    {
       std::stringstream ss;
    
       for (unsigned int m = 0; m < 101; ++m)
       {
          ss.clear();
    
          unsigned int t = m;
    
          for (unsigned int i = 0; i < 4; ++i)
          {
             unsigned char c = t;
             ss << c;
             t >>= 8;
          }
    
          unsigned int n = 0;
    
          for (unsigned int i = 0, j = 0; i < 4; ++i, j += 8)
          {
             unsigned char c;
             ss >> c;
             n = n | (c << j);
          }
    
          if (n != m)
             std::cout << "not working for " << m << std::endl;
       }
    }
    

    这就是结果。

    not working for 9
    not working for 10
    not working for 11
    not working for 12
    not working for 13
    not working for 32
    
    1 回复  |  直到 2 年前
        1
  •  3
  •   Sam Varshavchik    2 年前

    花点时间盯着那些“无效”的价值观看。如果你盯着他们看足够长的时间,他们会突然看起来非常熟悉。

    你会注意到,在ASCII表中,所有这些都对应于空白字符:NL、CR、FF、VT,还有我最喜欢的字符:SP,空格字符,ASCII代码32(我想我错过了一个,我只是懒得查…)

    >> ,在流上,自动丢弃所有空白字符。如果你的目标是读写个人 char 值,到流,您不想使用 << >> 。您想使用 read() write() 方法。

    (好吧,你可能会用 << ,但为了保持一致,只需使用 read write )。

    推荐文章