Erk
Erk

Reputation: 79

C++ converting an int to a string

I know this is extremely basic but I'm very new to C++ and can't seem to find an answer. I'm simply trying to convert a few integers to strings. This method works:

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

but when I need to convert the second and third ones like this:

int b = 13;
stringstream ss;
ss << a;
string str2 = ss.str();

int c = 15;
stringstream ss;
ss << b;
string str3 = ss.str();

I get this error:

'std::stringstream ss' previously declared here

Do I need to somehow close stringstream? I've noticed that if I put them far away from each other in my code the compiler doesn't mind but that doesn't seem like something I should do. Does anyone have suggestions?

Upvotes: 4

Views: 66650

Answers (6)

Potatoswatter
Potatoswatter

Reputation: 137910

The stringstream is a variable just like any other. To make the idiom work twice without change, put it in braces:

int a = 13;
string str2;
{
    stringstream ss;
    ss << a;
    str2 = ss.str();
} // ss ceases to exist at the closing brace

int b = 15;
string str3;
{
    stringstream ss; // now we can make a new ss
    ss << b;
    str3 = ss.str();
}

Since C++11, you can do

std::string str4 = std::to_string( b );

or (with c of arbitrary type)

std::string str5 = ( std::stringstream() << c ).str();

There are other solutions, of course.

Upvotes: 3

4aRk Kn1gh7
4aRk Kn1gh7

Reputation: 4359

One of the simplest way i can think of doing it is:

string str = string(itoa(num));

Upvotes: 0

Joe
Joe

Reputation: 104

Make sure you declare:

using namespace std;

Then insert the code:

int a = 10;
ostringstream ssa;
ssa << a;
string str = ssa.str();

int b = 13;
ostringstream ssb;
ssb << b;
string str2 = ssb.str();

int c = 15;
ostringstream ssc;
ssc << c;
string str3 = ssc.str();

Upvotes: 0

d.moncada
d.moncada

Reputation: 17402

try

#include <string>

int a = 10;
std::string s = std::to_string(a);

Upvotes: 1

Bdloul
Bdloul

Reputation: 902

You're trying to redeclare the same stringstream with the same name. You can modify your code like this in order to work :

 int b = 13;
stringstream ss2;
ss2 << a;
string str2 = ss2.str();

Or like this if you don't want to redeclare it :

int b = 13;
ss.str(""); // empty the stringstream
ss.clear();
ss << a;
string str2 = ss.str();

You can also use , which is much quicker :

int c = 42;
std::string s = std::to_string(c);

Upvotes: 9

Mike Dinescu
Mike Dinescu

Reputation: 55760

The particular error you are getting is telling you that you can't declare two variables with the same name (ss in your case) within the same scope.

If you wanted to create a new stringstream you could call it something else.

But there are other ways to convert an int to a string.. you could use std::to_string().

Upvotes: 1

Related Questions