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

C++ Data Conversion

Status
Not open for further replies.

nhungr

Programmer
Jan 31, 2005
26
CA
How do I convert an integer variable to a char that can be displayed onto the screen? For example, this is the code I'm using, but it won't write out the value of the integer:

int anynum = 0;
char mymessage[30]={0};

strcpy(mymessage,"My number is: ");
strcat(mymessage,anynum);

cout << mymessage;

The error occurs at the strcat function, because anynum is the wrong datatype. How do I convert it?

Thanks...
 
Code:
int anyNum = 0;
char myMessage[30] = {0};

strcpy(myMessage,"My number is:")

cout << myMessage << anynum;

"If it could have gone wrong earlier and it didn't, it ultimately would have been beneficial for it to have." : Murphy's Ultimate Corollary
 
(;):
Code:
cout << "My number is:" << anynum << endl;
 
or
Code:
sprintf(myMessage,"My number is:%d",anyNum)
cout << myMessage;


"If it could have gone wrong earlier and it didn't, it ultimately would have been beneficial for it to have." : Murphy's Ultimate Corollary
 
In order to convert int to char you must use a cast. The following will work for single digit numbers. (48 is the ASCII code for 0)


int main()
{
int num = 5;
char num2 = char(num) + 48;
cout <<"num is: "<< num << "\n" << "num2 is: " << num2 << endl;

return 0;
}


in order to convert numbers greater than 10 you have to use a string and the code becomes a bit more complicated but you should be able to figure it out.
 
Look up string streams in your handy manual / book.


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top