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

早过忘川 提交于 2020-02-03 11:57:41

问题


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

回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/7537874/how-do-you-convert-an-int-into-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!