Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream string to int

Tags:

c++

The C++ code below does int to string and a string to int conversions. Then, it repeats these steps again. The stringstream to int line stream1 >> i3; is breaking the code. What am I missing here?

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

int main()
{
 int i1 = 101;
 int i2 = 202;
 int i3 = 0;
 string s1 = "";
 string s2 = "";
 stringstream stream1;

 for (int i=0;i<2;i++)
 {

   //int to string
   stream1.str("");
   cout << "i1 " << i1 << endl;
   stream1 << i1;
   s1 = stream1.str();
   cout << "s1 " << s1 << endl;

   //int to string
   cout << "i2 " << i2 << endl;
   stream1.str("");
   stream1 << i2;
   s2 = stream1.str();
   cout << "s2 " << s2 << endl;

   //string to int
   stream1.str("");
   stream1.str(s2);
   stream1 >> i3;
   //line above causes s1 and s2 to get messed up during 2nd time in for loop
   cout << "i3-- " << i3 << endl;

  }
  return 0;
 }
like image 219
user584583 Avatar asked Mar 29 '11 17:03

user584583


People also ask

Can you cast a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

Is Stringstream a string?

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.


Video Answer


2 Answers

I tested your code and could reproduce the problem. I solved it inserting a .clear() before .str("")

Have a look here: How to reuse an ostringstream?

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

int main()
{
 int i1 = 101;
 int i2 = 202;
 int i3 = 0;
 string s1 = "";
 string s2 = "";
 stringstream stream1;

 for (int i=0;i<2;i++)
 {

   //int to string
   stream1.clear();
   stream1.str("");
   cout << "i1 " << i1 << endl;
   stream1 << i1;
   s1 = stream1.str();
   cout << "s1 " << s1 << endl;

   //int to string
   cout << "i2 " << i2 << endl;
   stream1.clear();
   stream1.str("");
   stream1 << i2;
   s2 = stream1.str();
   cout << "s2 " << s2 << endl;

   //string to int
   stream1.clear();
   stream1.str("");
   stream1.str(s2);
   stream1 >> i3;
   //line above causes s1 and s2 to get messed up during 2nd time in for loop
   cout << "i3-- " << i3 << endl;

  }
  return 0;
 }
like image 67
Javi R Avatar answered Oct 13 '22 01:10

Javi R


The problem is that the stream's EOF flag is being set while extracting the integer (i.e. stream1.eof() returns true), but you never clear it. Inserting a call to stream1.clear() after extraction fixes your issue.

like image 27
ildjarn Avatar answered Oct 13 '22 02:10

ildjarn