How to push_back an integer to a string?

assignment_operator picture assignment_operator · Oct 6, 2013 · Viewed 8k times · Source

Right now, I'm preparing to do a homework assignment by first sorting out what I'm going to do in my methods. For one of them, I have to prepare a list of names to be added to a list in the form A1, B2, C3 ... etc. What I am testing right now is a way to add them via a for loop. Please note that I am not doing the whole thing yet, I'm just ensuring that the items are made in the correct form. I have the following code:

list<string> L; //the list to hold the data in the form A1, B2, etc.
char C = 'A'; //the char value to hold the alphabetical letters
for(int i = 1; i <= 5; i++)
{ 
    string peas; //a string to hold the values, they will be pushed backed here
    peas.push_back(C++); //adds an alphabetical letter to the temp string, incrementing on every loop
    peas.push_back(i); //is supposed to add the number that i represents to the temp string
    L.push_back(peas); //the temp string is added to the list
}

The letter chars add and increment to the value just fine (they show up as A B C etc.), but the problem I am having is that when I push_back the integer value, it doesn't actually push_back an integer value, but an ascii value related to the integer (that's my guess -- it returns emoticons).

I'm thinking the solution here is to turn the integer value into a char, but, so far, looking that up has been very confusing. I have tried to_string (gives me errors) and char(i) (same result as just i) but none have worked. So basically: how can I add i as a char value representing the actual integer number it holds and not as an ascii value?

My TA usually doesn't actually read the code sent to him and the instructor takes far too long to respond, so I was hoping I could get this issue resolved here.

Thank you!

Answer

Konrad Rudolph picture Konrad Rudolph · Oct 6, 2013

push_back appends individual characters to the string. What you want is to convert a number to a string and then concatenate this string to another string. That’s a fundamentally different operation.

To convert a number to a string, use to_string. To concatenate strings, you can simply use +:

std::string prefix = std::string(1, C++);
L.push_back(prefix + std::to_string(i));

If your compiler doesn’t support C++11 yet, there’s the solution using a stringstream:

std::ostringstream ostr;
ostr << C++ << i;
L.push_back(ostr.str());