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

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 6 years ago.
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?

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

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.

printf("Player %d", i);
(Downvote my answer all you like; I still hate the C++ I/O operators.)
:-P

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;

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;

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

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.

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;

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

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 ;

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

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

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.

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

You can use the following
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);

If using Windows/MFC, and need the string for more than immediate output try:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);

Related

how to put "a string",a number,"a string",another number in a string arra

I have question about putting data below in a string array , I mean that is it possible to do as bellow:
for(int i{};i<num;i++)
string[i]={"The degree of",i,"'th vertice is",degree[i]}
I have tried that and I know its not practical in c++ but is there any other way to do so, my goal is to return a string that number of each degree is saved in by a function called degree,as what I have mentioned (for example "The degree of 4'th vertice is 2") .
so is there possible to do so?
I want to call the function as below:
std::cout<<degree();
thanks for your attention.
Sure, you can put everything in a single string and put a newline ('\n') between each logical line. Just combine the code snippets given above:
std::string degrees()
{
std::string lines;
for(int i{};i<num;i++)
lines += "The degree of " + std::to_string(i) +
"'th vertice is " + std::to_string(degree[i]) + '\n';
return lines;
}
You could try something like this as well (edited to remove argument passing to degrees fnc, as OP doesn't want that):
#include <iostream>
#include <sstream>
std::vector<int> degree = { 1,5,4,8,2,12,4,30,45,22 };
std::string degrees()
{
std::ostringstream oss;
for (size_t i = 0; i < degree.size(); ++i)
oss << (i > 0 ? "\n" : "") << "The degree of " << i + 1 << "'th vertice is " << degree[i];
return oss.str();
}
int main()
{
std::cout << degrees() << std::endl;
return 0;
}
Prints:

cout and String concatenation

I was just reviewing my C++. I tried to do this:
#include <iostream>
using std::cout;
using std::endl;
void printStuff(int x);
int main() {
printStuff(10);
return 0;
}
void printStuff(int x) {
cout << "My favorite number is " + x << endl;
}
The problem happens in the printStuff function. When I run it, the first 10 characters from "My favorite number is ", is omitted from the output. The output is "e number is ". The number does not even show up.
The way to fix this is to do
void printStuff(int x) {
cout << "My favorite number is " << x << endl;
}
I am wondering what the computer/compiler is doing behind the scenes.
The + overloaded operator in this case is not concatenating any string since x is an integer. The output is moved by rvalue times in this case. So the first 10 characters are not printed. Check this reference.
if you will write
cout << "My favorite number is " + std::to_string(x) << endl;
it will work
It's simple pointer arithmetic. The string literal is an array or chars and will be presented as a pointer. You add 10 to the pointer telling you want to output starting from the 11th character.
There is no + operator that would convert a number into a string and concatenate it to a char array.
adding or incrementing a string doesn't increment the value it contains but it's address:
it's not problem of msvc 2015 or cout but instead it's moving in memory back/forward:
to prove to you that cout is innocent:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char* str = "My favorite number is ";
int a = 10;
for(int i(0); i < strlen(str); i++)
std::cout << str + i << std::endl;
char* ptrTxt = "Hello";
while(strlen(ptrTxt++))
std::cout << ptrTxt << std::endl;
// proving that cout is innocent:
char* str2 = str + 10; // copying from element 10 to the end of str to stre. like strncpy()
std::cout << str2 << std::endl; // cout prints what is exactly in str2
return 0;
}

C++ snippet OK with MSVC but not with g++

I'm new to C++ and I try to adapt a program snippet which generates "weak compositions" or Multisets found here on stackoverflow but I run - to be quite frank - since hours into problems.
First of all, the program runs without any complaint under MSVC - but not on gcc.
The point is, that I have read many articles like this one here on stackoverflow, about the different behaviour of gcc and msvc and I have understood, that msvc is a bit more "liberal" in dealing with this situation and gcc is more "strict". I have also understood, that one should "not bind a non-const reference to a temporary (internal) variable."
But I am sorry, I can not fix it and get this program to work under gcc - again since hours.
And - if possible - a second question: I have to introduce a global variable
total, which is said to be "evil", although it works well. I need this value of total, however I could not find a solution with a non-global scope.
Thank you all very much for your assistance.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int total = 0;
string & ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut = string(), string strBuild = string()) {
unsigned au4;
if (au4Boxes > 1) for (au4 = 0; au4 <= au4Balls; au4++)
{
stringstream ss;
ss << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls - au4;
ListMultisets(au4Boxes - 1, au4, strOut, ss.str());
}
else
{
stringstream ss;
ss << mycount << ".\t" << "(" << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls << ")\n";
strOut += ss.str();
total++;
}
return strOut;
}
int main() {
cout << endl << ListMultisets(5,3) << endl;
cout << "Total: " << total << " weak compositions." << endl;
return 0;
}
C++ demands that a reference parameter to an unnamed temporary (like string()) must either be a const reference or an r-value reference.
Either of those reference types will protect you from modifying a variable that you don't realize is going to be destroyed within the current expression.
Depending on your needs, it could would to make it a value parameter:
string ListMultisets( ... string strOut = string() ... ) {
or it could would to make it a function-local variable:
string ListMultisets(...) {
string strOut;
In your example program, either change would work.
Remove the default value for the strOut parameter.
Create a string in main and pass it to the function.
Change the return type of the function to be int.
Make total a local variable ListMultisets(). Return total rather than strOut (you are returning the string value strOut as a reference parameter.)
The signature of the new ListMultisets will look like:
int ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut)
I'll let you figure out the implementation. It will either be easy or educational.
Your new main function will look like:
int main() {
string result;
int total = ListMultisets(5,3, result);
cout << endl << result << endl;
cout << "Total: " << total << " weak compositions." << endl;
return 0;
}

Save Int Data into Text File in C++

I working on saving Data into text file and compare it with another text file. Below is the code I worked on:
ofstream outfile;
outfile.open("Data",ios::out | ios :: binary);
for(x=0; x<100; x++)
{
printf("data- %x\n", *(((int*)pImagePool)+x));
int data = *(((int*)pImagePool)+x);
//outfile<<(reinterpret_cast<int *>(data))<<endl;
outfile<<(int *)data<<endl;
}
The result from printf is 24011800 and result read from text file is 0x24011800
Why there is 0x appeared? Do we able to remove it?
What is the difference between reinterpret_cast<int *> & (int *) but both giving the same result?
It's because you cast it as a pointer, so the output will be a pointer.
Since data is a normal value variable, just write it as usual:
outfile << data << '\n';
I also recommend you stop using printf when programming C++, there no reason to use it. Instead output using std::cout:
std::cout << "data- " << *(((int*)pImagePool)+x) << '\n';
Or if you want hexadecimal output
std::cout << "data- " << std::hex << *(((int*)pImagePool)+x) << '\n';
"%x" is a specifier for a hexadecimal number. Check this table: http://www.cplusplus.com/reference/cstdio/printf/
Use "%d" to output a decimal.
EDIT: About the casting, see this:
Reinterpret_cast vs. C-style cast
This is a very simple example using the ofstream f. The most complicated part are the parameters passed to the open, specifically std::ios::out which specifies the file direction. You could also use std::ios:in for reading from a file along with cin.
// ex5.cpp
#include <string>
#include <iostream>
#include <fstream>
#include "hr_time.hpp"
#include >ios>
int main(int argc, char * argv[])
{
CStopWatch sw;
sw.startTimer() ;
std::ofstream f;
f.open("test.txt",std::ios::out ) ;
for (int i=0;i<100000;i++)
{
f << "A very long string that is number " << i << std::endl;
}
f.close() ;
sw.stopTimer() ;
std::cout << "This took " << sw.getElapsedTime() << " seconds" << std::endl;
return 0;
}

Formatting C++ output problem

Let me examplify my problem , I've a function like:
void printer(int width, int hight){
for(int i=0;i<width;++i) std::cout<<" & ";
for(int i=0;i<hight;++i) std::cout<<" ^ ";
std::cout<<std::endl;
}
my problem is function printer should always output of both for loop in same width
e.g:
output could look (width 5):
&^
&&&^
or there is anyway that i print any of (from above code) for loop's output in constant width independent of no of times for loop executes
Question is unclear. Are you looking for something like the following ?
void printer(int amps, int carets, int overallWidth){
for (int i = amps + carets; i < overallWidth; i++) std::cout<<" "; // leading padding
for (int i=0;i<amps;++i) std::cout<<"&";
for (int i=0;i<carets;++i) std::cout<<"^";
std::cout<<std::endl;
}
The change was just to add a loop for outputting the padding. (also changed the parameters name for clarity)
printer(1,1,5);
printer(3,1,5);
would then produce the output shown in example
&^
&&&^
and of course, rather than being passed as a parameter, the overallWidth variable could be hardcoded; an implicit constant of the printer() function.
Edit:
The snippet above stayed very close to that of the question. There are however more idiomatic approaches, for example the following "one liner", which uses one of the string constructor overloads to produce the strings of repeated characters, and iomanip's setw() to produce the padding.
void printer(int amps, int carets, int overallWidth){
std::cout << setiosflags(ios::right) << setw(overalWidth)
<< string(amps, '&') + string (carets, '^')
<< std::endl;
}
Look into <iomanip>. Using cout you can specify a width.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setiosflags(ios::left) << setw(10) << "Hello"
<< setiosflags(ios::right) << setw(20) << "World!";
return 0;
}