gpt4 book ai didi

c++ - stringstream:dec int 到 hex 到 car 的转换问题

转载 作者:行者123 更新时间:2023-11-30 05:28:42 28 4
gpt4 key购买 nike

当我遇到这个问题时,我正在尝试使用 stringstream 进行一些简单的练习。下面的程序接受一个 int 数,将其以十六进制格式保存在 stringstream 中,然后显示十进制 int 和 char 是否可用 string。我为不同的输入运行它,但其中一些输入无法正常工作。详情请看下面的代码:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main() {
int roll;
stringstream str_stream;
cout << "enter an integer\n";
cin>>roll;
str_stream << hex << roll;

if(str_stream>>dec>>roll){
cout << "value of int is " << roll << "\n";
}
else
cout << "int not fount \n";
char y;

if(str_stream>>y){
cout << "value of char is "<< y << endl;
}
else
cout << "char not found \n";
cout << str_stream.str() << "\n";
}

我针对 3 个不同的输入运行它: 案例 1:
{
输入一个整数
9
int 的值为 9
找不到字符
9

案例 2:
输入一个整数
31
int 的值为 1
char 的值为 f
1f

案例 3:
输入一个整数
12
int 不是字体
找不到字符
c

案例 1 和 2。程序按预期工作,但在情况 3 中,它应该找到一个字符,我不确定为什么它无法在流中找到字符。

问候,纳维尼语

最佳答案

如果 if(str_stream>>dec>>roll) 无法读取任何内容,则流的状态将设置为 fail(false)。之后,除非您使用 clear() 重置流的状态,否则使用该流的任何进一步读取操作都不会成功(并返回 false)。

所以:

 .....//other code
if(str_stream>>dec>>roll){
cout << "value of int is " << roll << "\n";
}
else
{
cout << "int not fount \n";
str_stream.clear();//*******clears the state of the stream,after reading failed*********
}
char y;

if(str_stream>>y){
cout << "value of char is "<< y << endl;
}
else
cout << "char not found \n";

....//other code

关于c++ - stringstream:dec int 到 hex 到 car 的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685535/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com