[英]How do you convert an int into a string in c++
I want to convert an int to a string so can cout it. 我想将一个int转换为一个字符串,所以可以cout它。 This code is not working as expected:
此代码未按预期工作:
for (int i = 1; i<1000000, i++;)
{
cout << "testing: " + i;
}
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 - 如果你仍然想知道如何将整数转换为字符串,那么以下是使用stringstream的方法 -
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int number = 123;
stringstream ss;
ss << number;
cout << ss.str() << endl;
return 0;
}
Use std::stringstream
as: 使用
std::stringstream
:
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;
}
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. 使用“endl”,因此每个语句将打印一个单独的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.