【问题标题】:stringstream: dec int to hex to car conversion issuestringstream:dec int 到 hex 到汽车的转换问题
【发布时间】: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


    【解决方案1】:

    如果if(str_stream&gt;&gt;dec&gt;&gt;roll) 无法读取任何内容,则流的状态设置为fail(false)。之后,使用该流的任何进一步读取操作都不会成功(并返回 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
    

    【讨论】:

    • 谢谢,使用fail()和clear()函数后,程序运行正常。
    猜你喜欢
    • 2013-08-07
    • 2015-11-18
    • 1970-01-01
    • 2012-03-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多