使用stringstream获取字节值

twk*_*twk 6 c++ iostream 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;
}
Run Code Online (Sandbox Code Playgroud)

我运行它时的输出是49,这不是我想看到的.显然,这被视为char而不是简单的数值.什么是c ++最常用的方法是在c转换为int时保持1而不是49?

谢谢!

Kon*_*lph 10

大多数C++ - ish方法肯定是通过读入另一个整数类型来正确解析值,然后转换为字节类型(因为读入char将永远不会解析 - 它将始终只读取下一个字符):

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);
Run Code Online (Sandbox Code Playgroud)

我用过,unsigned int因为那是最自然的,虽然unsigned short当然也可以.