RetroCoder
RetroCoder

Reputation: 2685

How do you convert an int into a string in c++

I want to convert an int to a string so can cout it. This code is not working as expected:

for (int i = 1; i<1000000, i++;)
{ 
    cout << "testing: " +  i; 
}

Upvotes: 3

Views: 4075

Answers (3)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

You should do this in the following way -

for (int i = 1; i<1000000, i++;)
{ 
    cout << "testing: "<<i<<endl; 
}

The << operator will take care of printing the values appropriately.

If you still want to know how to convert an integer to string, then the following is the way to do it using the stringstream -

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    int number = 123;
    stringstream ss;

    ss << number;
    cout << ss.str() << endl;

    return 0;
}

Upvotes: 10

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

Use std::stringstream as:

for (int i = 1; i<1000000, i++;)
{
  std::stringstream ss("testing: ");
  ss << i;

  std::string s = ss.str();
  //do whatever you want to do with s
  std::cout << s << std::endl; //prints it to output stream
}

But if you just want to print it to output stream, then you don't even need that. You can simply do this:

for (int i = 1; i<1000000, i++;)
{
   std::cout << "testing : " << i;
}      

Upvotes: 5

Alex B
Alex B

Reputation: 84812

Do this instead:

for (int i = 1; i<1000000, i++;)
{
    std::cout << "testing: " <<  i << std::endl;
}

The implementation of << operator will do the necessary conversion before printing it out. Use "endl", so each statement will print a separate line.

Upvotes: 2

Related Questions