【问题标题】:Getting a byte value using stringstream使用 stringstream 获取字节值
【发布时间】:2010-07-28 19:27:03
【问题描述】:

我有这个(不正确的)示例代码,用于从 stringstream 中获取一个值并将其存储在一个字节大小的变量中(它需要在一个单字节 var 中,而不是 int 中):

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char** argv)
{
    stringstream ss( "1" );

    unsigned char c;
    ss >> c;

    cout << (int) c << endl;
}

我运行它时的输出是 49,这不是我希望看到的。显然,这被视为 char 而不是简单的数值。当转换为 int 时,让 c 保持 1 而不是 49 的最 c++ 方式是什么?

谢谢!

【问题讨论】:

  • 试试字符串:“\01”。或者设置一个 char 数组,用 { 1, 0 } 初始化

标签: c++ iostream stringstream


【解决方案1】:

最 C++ 的方式当然是通过读入另一个整数类型来正确解析值,然后然后转换为字节类型(因为读入@ 987654321@ 永远不会解析——它只会读取下一个字符):

typedef unsigned char byte_t;

unsigned int value;
ss >> value;
if (value > numeric_limits<byte_t>::max()) {
    // Error …
}

byte_t b = static_cast<byte_t>(value);

我使用了unsigned int,因为这是最自然的方法,尽管unsigned short 当然也可以。

【讨论】:

  • 感谢您的回复。我希望有一些格式化标志,但演员也可以。
【解决方案2】:

一个字符总是会这样做。您需要读取一个 int(或 float 或 double 等),否则将调用错误的“格式化程序”。

unsigned char c;
unsigned int i;
ss >> i;
c = i;

【讨论】:

    【解决方案3】:

    从中减去'0'

    cout << (int) (c - '0') << endl;
    

    '0' 的值为 48,因此 49 - 48 = 1

    【讨论】:

    • 不幸的是,我需要将正确的值存储在实际 var 中。
    【解决方案4】:
    stringstream ss( "1" );
    unsigned char c;
    {
        unsigned int i;
        ss >> i;
        c = i;
    }
    cout << static_cast<int>(c) << endl;
    

    会工作。你也可以做一些不安全的指针的事情,但我会选择上面的。

    【讨论】:

      【解决方案5】:

      这是因为 C++ 中的字符串常量被视为文本。
      两种选择:

      • 使用转义数字对字符串进行编码:

        • 八进制数:\0{1,3}
        • 十六进制数:\0x{2}

        std::stringstream("\01\02\03\04\0xFF");

      • 或者构建一个 char 数组并使用数字对其进行初始化:

        字符数据[] = { 0, 1, 2,3 ,4, 255 };

      怎么样:

      #include <iostream>
      #include <sstream>
      
      using namespace std;
      
      int main(int argc, char** argv)
      {
          char x[] = {1,0};
          stringstream ss( x);
      
          unsigned char c;
          ss >> c;
      
          cout << (int) c << endl;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        • 1970-01-01
        • 2013-04-21
        • 1970-01-01
        • 2015-02-20
        相关资源
        最近更新 更多