Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using string with ints?

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
hello i am trying to create an appended string

int i = 5;
char * ch = 3;
string st;

can i do....

st += ch;
st += i;

that is, append a integer or another data type to a string like this..
i know i can use sstream to do this but i need to be able to use string.

cheers
 
I would format using sprintf (havent used "string" in a while and you may need to get a writeable buffer, i forget)

sprintf(string,"%c%d",ch,i);

Matt
 
If possible I'd still recommend sstream, as its the C++ way to do it, which type checks and so on.

sprintf has no type checking at all.

>i need to be able to use string.

sstream to string is trivial

/Per

"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."
 
sprintf doesn't work with string anyway. And char * ch = 3; is not right either. You'll just have to use a stringstream if you use a string. Note that even eith c-style strings you cannot use += either, you must use strcat or sprintf.
 
> i know i can use sstream to do this but i need to be able to use string.

sstream (i.e. stringstream) is string-based. You just haven't looked at a reference for how to use it.

So:

Code:
stringstream s;

s << 5 << " bleat " << 4.78 << '?';

string str = s.str();

/* ... */

string woof( "I like eating " );

stringstream r( woof );

r << get_num_cats() << " cats a day\n";
 
There is a very strange code in the 1st post:
Code:
char * ch = 3;
Assign int to pointer?...
Proposed 'solution
Code:
sprintf(string,"%c%d",ch,i);
crashes your string, that's all...
Use sprintf via temp buffer:
Code:
void operator +=(string& s, int i)
{
  char temp[12];
  sprintf(temp,"%d",i);
  s += temp;
}
Now you may use string += int as you wish...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top