c++ - How to push_back an integer to a string? -


right now, i'm preparing homework assignment first sorting out i'm going in methods. 1 of them, have prepare list of names added list in form a1, b2, c3 ... etc. testing right way add them via loop. please note not doing whole thing yet, i'm ensuring items made in correct form. have following code:

list<string> l; //the list hold data in form a1, b2, etc. char c = 'a'; //the char value hold alphabetical letters for(int = 1; <= 5; i++) {      string peas; //a string hold values, pushed backed here     peas.push_back(c++); //adds alphabetical letter temp string, incrementing on every loop     peas.push_back(i); //is supposed add number represents temp string     l.push_back(peas); //the temp string added list } 

the letter chars add , increment value fine (they show b c etc.), problem having when push_back integer value, doesn't push_back integer value, ascii value related integer (that's guess -- returns emoticons).

i'm thinking solution here turn integer value char, but, far, looking has been confusing. have tried to_string (gives me errors) , char(i) (same result i) none have worked. basically: how can add char value representing actual integer number holds , not ascii value?

my ta doesn't read code sent him , instructor takes far long respond, hoping issue resolved here.

thank you!

push_back appends individual characters string. want convert number to string , concatenate string string. that’s fundamentally different operation.

to convert number string, use to_string. concatenate strings, can use +:

std::string prefix = std::string(1, c++); l.push_back(prefix + std::to_string(i)); 

if compiler doesn’t support c++11 yet, there’s solution using stringstream:

std::ostringstream ostr; ostr << c++ << i; l.push_back(ostr.str()); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -