Search code examples
c++charhexstringstream

stringstream: dec int to hex to car conversion issue


I was trying some simple exercises with stringstream, when I came across this problem. Following program takes an int number, saves it in stringstream in hex format and then displays whether a int in decimal and char are available in string. I ran it for different inputs and it is not working properly for some of them. Please see the detail below code:

#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";
}

I ran it for 3 different inputs: Case1: { enter an integer 9 value of int is 9 char not found 9

Case2: enter an integer 31 value of int is 1 value of char is f 1f

Case3: enter an integer 12 int not fount char not found c

In case 1 &2. program is working as expected but in case 3, it should found a char, I am not sure why it is not able to find char in stream.

Regards, Navnish


Solution

  • If if(str_stream>>dec>>roll) fails to read anything then the state of the stream is set to fail(false). After that any further read operation using that stream will not be successful(and returns false) unless you reset the state of the stream using clear().

    So:

     .....//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