[c++] How do you append an int to a string in C++?

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?

This question is related to c++ int stdstring

The answer is


cout << text << " " << i << endl;

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:

cout << text;
cout << i;

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


Well, if you use cout you can just write the integer directly to it, as in

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.

#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.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

This also works the other way around, i.e. to parse strings.


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:

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

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.

For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.


cout << text << " " << i << endl;

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:

cout << text;
cout << i;

cout << "Player" << i ;

You also try concatenate player's number with 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


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

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


}

If using Windows/MFC, and need the string for more than immediate output try:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);

printf("Player %d", i);

(Downvote my answer all you like; I still hate the C++ I/O operators.)

:-P


cout << text << " " << i << endl;

cout << "Player" << i ;

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.


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:

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

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.

For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.


cout << text << i;

With C++11, you can write:

#include <string>     // to use std::string, std::to_string() and "+" operator acting on strings 

int i = 4;
std::string text = "Player ";
text += std::to_string(i);

Another possibility is 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;
}

For the record, you could also use Qt's QString class:

#include <QtCore/QString>

int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData();  // prints "Player 4"

With C++11, you can write:

#include <string>     // to use std::string, std::to_string() and "+" operator acting on strings 

int i = 4;
std::string text = "Player ";
text += std::to_string(i);

For the record, you can also use a std::stringstream if you want to create the string before it's actually output.


Well, if you use cout you can just write the integer directly to it, as in

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.

#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.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

This also works the other way around, i.e. to parse strings.


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:

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

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.

For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.


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


You can use the following

int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);

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).


Another possibility is 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;
}

cout << text << i;

For the record, you could also use Qt's QString class:

#include <QtCore/QString>

int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData();  // prints "Player 4"

cout << text << " " << i << endl;

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:

cout << text;
cout << i;

For the record, you can also use a std::stringstream if you want to create the string before it's actually output.


You also try concatenate player's number with 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


For the record, you can also use a std::stringstream if you want to create the string before it's actually output.


cout << text << " " << i << endl;

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:

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

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.

For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.


For the record, you can also use a std::stringstream if you want to create the string before it's actually output.


cout << text << i;

printf("Player %d", i);

(Downvote my answer all you like; I still hate the C++ I/O operators.)

:-P


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

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


}

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

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 (for example, cout), rather than std::string
someStream << MyInt;

cout << text << i;

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

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 (for example, cout), rather than std::string
someStream << MyInt;

Well, if you use cout you can just write the integer directly to it, as in

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.

#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.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

This also works the other way around, i.e. to parse strings.


cout << "Player" << i ;

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:

cout << text;
cout << i;

printf("Player %d", i);

(Downvote my answer all you like; I still hate the C++ I/O operators.)

:-P


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.


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

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 (for example, cout), rather than std::string
someStream << MyInt;

You can use the following

int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);

cout << text << " " << i << endl;

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).


If using Windows/MFC, and need the string for more than immediate output try:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);

printf("Player %d", i);

(Downvote my answer all you like; I still hate the C++ I/O operators.)

:-P


cout << text << " " << i << endl;

cout << "Player" << i ;

Well, if you use cout you can just write the integer directly to it, as in

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.

#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.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

This also works the other way around, i.e. to parse strings.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to stdstring

Is it possible to use std::string in a constexpr? Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’ Remove First and Last Character C++ Concatenating strings doesn't work as expected What does string::npos mean in this code? How to replace all occurrences of a character in string? std::string formatting like sprintf convert a char* to std::string How to get the number of characters in a std::string? c++ integer->std::string conversion. Simple function?