Jump to content

[Solved] Char Questions


Holloweye
 Share

Recommended Posts

1. How can I add a int with a char? Like:
int x = 5;
char a;
a = x;

How is that an addition? Do you mean you want to assign an int to a char? Then your code should work. You can also do an explicit conversion:

int x = 5;
char a;
a = (char)x;

 

For 2.:

char a[80];
strcpy(a, "HELLO ");
strcat (a, "WORLD");

Link to comment
Share on other sites

You want either itoa or sprintf to convert the integer 5 to the string "5". As it is you're telling it to try and make a string out of whatever is at a memory location, which will cause a crash.

 

Probably something like this:

 

int i = 5;
char a[30];
strcpy(a, "SCORE ");
char buffer[30];
itoa (i,buffer,10);
strcat(a, buffer);

Windows 7 x64 - Q6700 @ 2.66GHz - 4GB RAM - 8800 GTX

ZBrush - Blender

Link to comment
Share on other sites

You want either itoa or sprintf to convert the integer 5 to the string "5". As it is you're telling it to try and make a string out of whatever is at a memory location, which will cause a crash.

 

Probably something like this:

 

int i = 5;
char a[30];
strcpy(a, "SCORE ");
char buffer[30];
itoa (i,buffer,10);
strcat(a, buffer);

 

 

Error:

main.c:81: warning: implicit declaration of function 'itoa'

 

I have #stdlib.h and string.h included. I guess there is no such function in C.

Link to comment
Share on other sites

int i = 5;
char a[30];
strcpy(a, "SCORE ");
char buffer[30];
itoa (i,buffer,10);
strcat(a, buffer);

That can be written much shorter:

int i=5;
char buffer[30];
sprintf(buffer,"SCORE %d",i);

Ryzen 9 RX 6800M ■ 16GB XF8 Windows 11 ■
Ultra ■ LE 2.53DWS 5.6  Reaper ■ C/C++ C# ■ Fortran 2008 ■ Story ■
■ Homepage: https://canardia.com ■

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...