使用stringstream获取字节值 [英] Getting a byte value using stringstream
问题描述
我有这个(不正确的)示例代码,用于从stringstream获取值,并将其存储在一个字节大小的变量(它需要在一个单一字节var,而不是一个int):
I've got this (incorrect) sample code for getting a value out of stringstream and storing it in a byte-sized variable (it needs to be in a single byte var, not an 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而不是简单的数值。什么是最c ++ ish的方式来获得c而持有1而不是49当被转换为int?
The output when I run this is 49, which is not what I would like to see. Obviously, this is being treated as a char and not simple numeric value. What is the most c++ish way to get c to hold a 1 rather than a 49 when casted to an int?
谢谢!
推荐答案
最C ++的方式肯定是通过读入另一个整数类型来正确解析值,然后 转换为字节类型(因为读入 char
永远不会解析 - 它总是只读取下一个字符):
The most C++-ish way is certainly to parse the value properly by reading into another integral type, and then cast to a byte type (since reading into a char
will never parse – it will always just read the next character):
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
最自然的,虽然未签名的短
当然也可以工作。
I’ve used unsigned int
since that’s the most natural, although unsigned short
would of course also work.
这篇关于使用stringstream获取字节值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!