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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do i convert char into a string (*char)

Status
Not open for further replies.

Xerxes333

Technical User
Mar 11, 2001
4
US
How Should I do this properly?
int main ( )
{
char *string="empty";
char item='2';
//at this point i am trying to convert 'h'
//into "h" so that i can use atoi( )

string=item;
cout << string << endl;
return 0;
}
Any and all help is greatly appreciated
 
I know this is true of C and am almost certain it is true of C++: you can't modify the string literal pointed to by string in your example -- doing so causes undefined behavior.

In this case, just assign it to the proper element of string:

char string[20];
char item='2';

string[0]=item;
string[1]='\0' /* Add the terminating null */

Now string is &quot;2&quot;





Russ
bobbitts@hotmail.com
 
Or, use sprintf... but Russ way is better (I think) this is more generic...

sprintf(string, &quot;%s&quot;, item);

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top