【发布时间】:2016-08-09 16:37:16
【问题描述】:
当我遇到这个问题时,我正在尝试使用 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 种情况下,它应该找到一个字符,我不确定为什么它无法在流中找到字符。
问候, 导航
【问题讨论】:
标签: c++ char hex stringstream