istringstream十进制整数输入到8位类型 [英] istringstream decimal integer input to 8-bit type

查看:281
本文介绍了istringstream十进制整数输入到8位类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这:

  #include< iostream> 
#include< sstream>
#include< inttypes.h>

using namespace std;

int main(void){
istringstream iss(123 42);
int8_t x;
while(iss>> x){
cout<< x < endl;
}
return 0;
}

产生:

  1 
2
3
4
2

但我想要:

  123 
42

铸造 iss>> (int)x (我最初尝试使用 char )给我错误: ('istringstream'(aka'basic_istringstream')and'int')(clang)或错误:对'operator >>' b

是否有一种方法可以将值直接读取为 8位类型,或者必须使用中间商店吗?

解决方案

您必须使用中间类型或自己解析。所有char类型(char,signed char和unsigned char)都被视为文本元素,而不是整数。



注意:




  • 输出会遇到相同的问题。

  • 不要使用C风格的转换,它们几乎只会导致错误。

  • 在输入操作之前检查EOF是无用的,您之后需要检查是否失败。


This:

#include <iostream>
#include <sstream>
#include <inttypes.h>

using namespace std;

int main (void) {
    istringstream iss("123 42");
    int8_t x;
    while (iss >> x) {
        cout << x << endl;
    }
    return 0;
}  

Produces:

1
2
3
4
2

But I want:

123
42

Casting iss >> (int)x (I initially tried this with a char) gives me "error: invalid operands to binary expression ('istringstream' (aka 'basic_istringstream') and 'int')" (clang) or "error: ambiguous overload for ‘operator>>’" (g++).

Is there a way to read the value as a number directly into an 8-bit type, or do I have to use an intermediary store?

解决方案

You have to use an intermediate type or do the parsing yourself. All char-types (char, signed char and unsigned char) are treated as text elements, not integers. int8_t is probably just a typedef for one of them, which is why your code fails.

Note:

  • The output will suffer from the same issues.
  • Don't use C-style casts, they almost only cause errors.
  • Checking for EOF before an input operation is useless, you need to check for failure afterwards instead.

这篇关于istringstream十进制整数输入到8位类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆