This question already has an answer here:
这个问题已经有了答案:
- How to concatenate a std::string and an int? 28 answers
- 如何连接std::string和int?28日答案
int i = 4;
string text = "Player ";
cout << (text + i);
I'd like it to print Player 4
.
我想把它打印出来。
The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?
上面的显然是错误的,但它表明了我在这里所要做的。有什么简单的方法可以做到这一点吗?还是我必须开始添加新的include ?
20 个解决方案
#1
188
With C++11, you can write:
用c++ 11,你可以写:
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
#2
183
Well, if you use cout you can just write the integer directly to it, as in
如果你用cout你可以直接把整数写进去
std::cout << text << i;
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
c++将各种对象转换为字符串的方法是通过字符串流。如果没有现成的,就创建一个。
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Alternatively, you can just convert the integer and append it to the string.
或者,您可以仅转换整数并将其附加到字符串。
oss << i;
text += oss.str();
Finally, the Boost libraries provide boost::lexical_cast
, which wraps around the stringstream conversion with a syntax like the built-in type casts.
最后,Boost库提供Boost::lexical_cast,它使用类似内置类型强制转换的语法来包装stringstream转换。
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
This also works the other way around, i.e. to parse strings.
这也是另一种方法,即解析字符串。
#3
108
printf("Player %d", i);
(Downvote my answer all you like, I still hate the C++ IO operators.)
(我对你的回答很失望,我仍然讨厌c++ IO操作系统。)
:-P
:- p
#4
19
these work for general strings (in case you do not want to output to file/console, but store for later use or something).
这些操作适用于一般的字符串(如果您不想将其输出到文件/控制台,而是存储以供以后使用或其他用途)。
boost.lexical_cast
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
string streams
字符串流
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
//if you're using a stream (eg cout), rather than std::string
someStream << MyInt;
#5
9
For the record, you can also use a std::stringstream
if you want to create the string before it's actually output.
对于记录,如果您想在字符串实际输出之前创建它,还可以使用std: stringstream。
#6
6
cout << text << " " << i << endl;
#7
3
Another possibility is Boost.Format:
另一种可能性是Boost.Format:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
#8
3
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
您的示例似乎表明您希望显示一个字符串后面跟着一个整数,在这种情况下:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
would work fine.
也可以。
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
但是,如果您要存储字符串位置或传递它,并且经常这样做,您可能会受益于重载加法操作符。我演示如下:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
In fact, you can use templates to make this approach more powerful:
事实上,您可以使用模板使此方法更强大:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Now, as long as object b
has a defined stream output, you can append it to your string (or, at least, a copy thereof).
现在,只要对象b有一个定义好的流输出,您就可以将它附加到您的字符串(或者,至少是它的一个副本)。
#9
2
Here a small working conversion/appending example, with some code I needed before.
这里有一个小型的工作转换/附加示例,其中包含一些我以前需要的代码。
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
the output will be:
的输出将会是:
/dev/video
/dev/video456
/dev/video321
/dev/video123
Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.
注意,在最后两行中,您将修改后的字符串保存到实际打印出来之前,如果需要,您可以稍后使用它。
#10
2
For the record, you could also use Qt's QString
class:
对于记录,您还可以使用Qt的QString类:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
#11
1
cout << text << i;
#12
1
cout << "Player" << i ;
#13
1
One method here is directly printing the output if its required in your problem.
这里的一个方法是直接打印输出,如果您的问题需要输出的话。
cout << text << i;
Else, one of the safest method is to use
否则,最安全的方法之一就是使用
sprintf(count, "%d", i);
And then copy it to your "text" string .
然后复制到你的“文本”字符串。
for(k = 0; *(count + k); k++)
{
text += count[k];
}
Thus, you have your required output string
因此,您有了所需的输出字符串
For more info on sprintf
, follow: http://www.cplusplus.com/reference/cstdio/sprintf
有关sprintf的更多信息,请参见:http://www.cplusplus.com/reference/cstdio/sprintf
#14
1
The easiest way I could figure this out is the following..
It will work as a single string and string array. I am considering a string array, as it is complicated (little bit same will be followed with string). I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps. length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int
我能想到的最简单的办法是……它将作为一个字符串和字符串数组工作。我考虑的是一个字符串数组,因为它很复杂(字符串后面也会跟着一个字符串)。我创建了一个名称数组,并添加了一些整数和字符,以显示在字符串中添加一些int和chars是多么容易,希望这能有所帮助。长度就是测量数组的大小。如果您熟悉编程,那么size_t是一个无符号整数
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}
#15
0
cout << text << i;
The <<
operator for ostream returns a reference to the ostream, so you can just keep chaining the <<
operations. That is, the above is basically the same as:
ostream的<< <运算符返回对ostream的引用,因此您可以继续链接<< <操作。也就是说,上面的内容基本上是一样的:< p>
cout << text;
cout << i;
#16
0
cout << text << " " << i << endl;
#17
-1
There are a few options, and which one you want depends on the context.
有几个选项,您想要哪个取决于上下文。
The simplest way is
最简单的方法是
std::cout << text << i;
or if you want this on a single line
或者你想在单行上写。
std::cout << text << i << endl;
If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.
如果您正在编写一个单线程程序,并且不经常调用该代码(其中“很多”是每秒数千次),那么就完成了。
If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:
如果您正在编写一个多线程程序,并且有多个线程正在编写cout,那么这个简单的代码可能会给您带来麻烦。假设编译器附带的库使cout线程足够安全,不会被中断。现在假设一个线程正在使用这个代码来编写“Player 1”,另一个线程正在编写“Player 2”。如果你幸运的话,你会得到以下信息:
Player 1
Player 2
If you are unlucky you might get something like the following
如果你不走运,你可能会得到如下的结果
Player Player 2
1
The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:
问题是std::cout < text < i < endl;变成3个函数调用。守则的内容如下:
std::cout << text;
std::cout << i;
std::cout << endl;
If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:
如果您使用c样式的printf,并且您的编译器提供了一个具有合理线程安全性的运行时库(每个函数调用都是原子的),那么下面的代码会更好:
printf("Player %d\n", i);
Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.
能够在单个函数调用中执行某些操作,可以让io库在幕后提供同步,现在您的整行文本将被原子化地编写。
For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.
对于简单的程序,std::cout很好。再加上多线程或其他复杂情况,不那么时髦的printf开始变得更有吸引力。
#18
-1
You also try concatenate player's number with std::string::push_back
:
您还可以尝试使用std:::string:::push_back:
Example with your code:
示例代码:
int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;
You will see in console:
您将在控制台看到:
Player 4
球员4
#19
-3
You can use the following
您可以使用以下内容
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
#20
-5
If using Windows/MFC, and need the string for more than immediate output try:
如果使用Windows/MFC,并且需要字符串多于立即输出,请尝试:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);
#1
188
With C++11, you can write:
用c++ 11,你可以写:
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
#2
183
Well, if you use cout you can just write the integer directly to it, as in
如果你用cout你可以直接把整数写进去
std::cout << text << i;
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
c++将各种对象转换为字符串的方法是通过字符串流。如果没有现成的,就创建一个。
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Alternatively, you can just convert the integer and append it to the string.
或者,您可以仅转换整数并将其附加到字符串。
oss << i;
text += oss.str();
Finally, the Boost libraries provide boost::lexical_cast
, which wraps around the stringstream conversion with a syntax like the built-in type casts.
最后,Boost库提供Boost::lexical_cast,它使用类似内置类型强制转换的语法来包装stringstream转换。
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
This also works the other way around, i.e. to parse strings.
这也是另一种方法,即解析字符串。
#3
108
printf("Player %d", i);
(Downvote my answer all you like, I still hate the C++ IO operators.)
(我对你的回答很失望,我仍然讨厌c++ IO操作系统。)
:-P
:- p
#4
19
these work for general strings (in case you do not want to output to file/console, but store for later use or something).
这些操作适用于一般的字符串(如果您不想将其输出到文件/控制台,而是存储以供以后使用或其他用途)。
boost.lexical_cast
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
string streams
字符串流
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
//if you're using a stream (eg cout), rather than std::string
someStream << MyInt;
#5
9
For the record, you can also use a std::stringstream
if you want to create the string before it's actually output.
对于记录,如果您想在字符串实际输出之前创建它,还可以使用std: stringstream。
#6
6
cout << text << " " << i << endl;
#7
3
Another possibility is Boost.Format:
另一种可能性是Boost.Format:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
#8
3
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
您的示例似乎表明您希望显示一个字符串后面跟着一个整数,在这种情况下:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
would work fine.
也可以。
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
但是,如果您要存储字符串位置或传递它,并且经常这样做,您可能会受益于重载加法操作符。我演示如下:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
In fact, you can use templates to make this approach more powerful:
事实上,您可以使用模板使此方法更强大:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Now, as long as object b
has a defined stream output, you can append it to your string (or, at least, a copy thereof).
现在,只要对象b有一个定义好的流输出,您就可以将它附加到您的字符串(或者,至少是它的一个副本)。
#9
2
Here a small working conversion/appending example, with some code I needed before.
这里有一个小型的工作转换/附加示例,其中包含一些我以前需要的代码。
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
the output will be:
的输出将会是:
/dev/video
/dev/video456
/dev/video321
/dev/video123
Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.
注意,在最后两行中,您将修改后的字符串保存到实际打印出来之前,如果需要,您可以稍后使用它。
#10
2
For the record, you could also use Qt's QString
class:
对于记录,您还可以使用Qt的QString类:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
#11
1
cout << text << i;
#12
1
cout << "Player" << i ;
#13
1
One method here is directly printing the output if its required in your problem.
这里的一个方法是直接打印输出,如果您的问题需要输出的话。
cout << text << i;
Else, one of the safest method is to use
否则,最安全的方法之一就是使用
sprintf(count, "%d", i);
And then copy it to your "text" string .
然后复制到你的“文本”字符串。
for(k = 0; *(count + k); k++)
{
text += count[k];
}
Thus, you have your required output string
因此,您有了所需的输出字符串
For more info on sprintf
, follow: http://www.cplusplus.com/reference/cstdio/sprintf
有关sprintf的更多信息,请参见:http://www.cplusplus.com/reference/cstdio/sprintf
#14
1
The easiest way I could figure this out is the following..
It will work as a single string and string array. I am considering a string array, as it is complicated (little bit same will be followed with string). I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps. length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int
我能想到的最简单的办法是……它将作为一个字符串和字符串数组工作。我考虑的是一个字符串数组,因为它很复杂(字符串后面也会跟着一个字符串)。我创建了一个名称数组,并添加了一些整数和字符,以显示在字符串中添加一些int和chars是多么容易,希望这能有所帮助。长度就是测量数组的大小。如果您熟悉编程,那么size_t是一个无符号整数
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}
#15
0
cout << text << i;
The <<
operator for ostream returns a reference to the ostream, so you can just keep chaining the <<
operations. That is, the above is basically the same as:
ostream的<< <运算符返回对ostream的引用,因此您可以继续链接<< <操作。也就是说,上面的内容基本上是一样的:< p>
cout << text;
cout << i;
#16
0
cout << text << " " << i << endl;
#17
-1
There are a few options, and which one you want depends on the context.
有几个选项,您想要哪个取决于上下文。
The simplest way is
最简单的方法是
std::cout << text << i;
or if you want this on a single line
或者你想在单行上写。
std::cout << text << i << endl;
If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.
如果您正在编写一个单线程程序,并且不经常调用该代码(其中“很多”是每秒数千次),那么就完成了。
If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:
如果您正在编写一个多线程程序,并且有多个线程正在编写cout,那么这个简单的代码可能会给您带来麻烦。假设编译器附带的库使cout线程足够安全,不会被中断。现在假设一个线程正在使用这个代码来编写“Player 1”,另一个线程正在编写“Player 2”。如果你幸运的话,你会得到以下信息:
Player 1
Player 2
If you are unlucky you might get something like the following
如果你不走运,你可能会得到如下的结果
Player Player 2
1
The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:
问题是std::cout < text < i < endl;变成3个函数调用。守则的内容如下:
std::cout << text;
std::cout << i;
std::cout << endl;
If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:
如果您使用c样式的printf,并且您的编译器提供了一个具有合理线程安全性的运行时库(每个函数调用都是原子的),那么下面的代码会更好:
printf("Player %d\n", i);
Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.
能够在单个函数调用中执行某些操作,可以让io库在幕后提供同步,现在您的整行文本将被原子化地编写。
For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.
对于简单的程序,std::cout很好。再加上多线程或其他复杂情况,不那么时髦的printf开始变得更有吸引力。
#18
-1
You also try concatenate player's number with std::string::push_back
:
您还可以尝试使用std:::string:::push_back:
Example with your code:
示例代码:
int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;
You will see in console:
您将在控制台看到:
Player 4
球员4
#19
-3
You can use the following
您可以使用以下内容
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
#20
-5
If using Windows/MFC, and need the string for more than immediate output try:
如果使用Windows/MFC,并且需要字符串多于立即输出,请尝试:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);