Lil Shaman Lil Shaman - 23 days ago 10
C Question

Printing elements of a char array with numbes and letters

I am trying to print out the elements of my char array which consists of both numbers and letters. My code is:

char *receiveInput(char *s) {
scanf("%99s", s);
return s;
}

int main() {
char str[100], inp[50] = "";
printf("Enter string");
receiveInput(str);
char cToStr[3];
int num = 3;
char c = (char)(num);
cToStr[0] = c;
cToStr[1] = str[0];
cToStr[2] = '\0';
strcat(inp, cToStr);
printf("%s\n", inp);
return 0;
}


Lets say str in
"hey"
,
inp
should contain and print
"3h
" but instead it just prints 'h' when cToStr[0] = c (which is a char 3).

How do I print the elements which contain both numbers and letters?

Answer

Number 3 is not the same as character '3'. For example in the ASCII table character '3' has integer code in hex 0x33 while in the EBCDIC table it has code 0xf3.

You can write

  int num = 3;
  char c = num + '0';
  cToStr[0] = c;

provided that num us less than 10.