Dear all,
How can add an integer variable to a string and char* variable? for example:
int a = 5;
string St1 = "Book", St2;
char *Ch1 = "Note", Ch2;
St2 = St1 + a --> Book5
Ch2 = Ch1 + a --> Note5
Thanks
I would recommend using stringstreams.
http://cplusplus.com/reference/iostream/stringstream/
I.e.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <string>
#include <sstream>
#include <iostream>
#include <string.h>
int main()
{
std::stringstream ss;
int a = 5;
std::string st1 = "Book";
std::string st2 = "";
char * ch1 = "Note";
char * ch2 = NULL;
ss<<st1<<a;
ss>>st2;
std::cout<<st2<<std::endl;
//clear the stream;
ss.clear();
ss.str("");
ss<<ch1<<a;
ch2 = new char [ss.str().length() + 1];
strcpy(ch2, ss.str().c_str());
std::cout<<ch2<<std::endl;
delete [] ch2;
return 0;
}
|
Edit... Read warnis's link and my post was covered there aswell.
Last edited on