stringstream:dec int 到 hex 到 car 的转换问题
stringstream: dec int to hex to car conversion issue
当我遇到这个问题时,我正在尝试使用 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 个不同的输入:
Case1:
{
enter an integer
9
value of int is 9
char not found
9
案例2:
enter an integer
31
value of int is 1
value of char is f
1f
案例 3:
enter an integer
12
int not fount
char not found
c
情况1&2。程序按预期工作,但在情况 3 中,它应该找到一个字符,我不确定为什么它无法在流中找到字符。
此致,
纳文
如果 if(str_stream>>dec>>roll)
无法读取任何内容,则流的状态设置为 fail(false)
。之后,除非您使用 clear()
.
重置流的状态,否则使用该流的任何进一步读取操作都不会成功(并且 returns 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
当我遇到这个问题时,我正在尝试使用 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 个不同的输入:
Case1:
{
enter an integer
9
value of int is 9
char not found
9
案例2:
enter an integer
31
value of int is 1
value of char is f
1f
案例 3:
enter an integer
12
int not fount
char not found
c
情况1&2。程序按预期工作,但在情况 3 中,它应该找到一个字符,我不确定为什么它无法在流中找到字符。
此致, 纳文
如果 if(str_stream>>dec>>roll)
无法读取任何内容,则流的状态设置为 fail(false)
。之后,除非您使用 clear()
.
所以:
.....//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