can't use sscanf() in C for char array
scanf
doesn't apply to characters. Once you have the characters just convert digits to integers by subtracting '0'
as a char:
for(int i=0; i<strlen(m); i++){
x = m[i] - '0'; // line to change
printf("%d",x);
}
Besides, just to make sure that the buffer won't overflow, 100 bytes is good, but you may want to use an according limit in scanf
and check the return code:
if (scanf("%99s",m) == 1) {
Using sscanf
to convert a single digit of a character string to an integer is the wrong approach. To do this, you only need to subtract the (integer) value of the representation of the character '0'
from that digit. Like this:
#include <stdio.h>
#include <string.h>
int main()
{
char m[50]; // As pointed out, a 4-digit number isn't really very long, so let's make it bigger
int x;
scanf("%49s", m); // Limit the input to the length of the buffer!
for (size_t i = 0; i < strlen(m); i++) { // The "strlen" function return "size_t"
x = m[i] - '0'; // The characters `0` thru `9` are GUARANTEED to be sequential!
printf("%d", x);
}
return 0;
}
scanf
doesn't apply to characters. Once you have the characters just convert digits to integers by subtracting '0'
as a char:
for(int i = 0; i < strlen(m); i++) {
x = m[i] - '0';
printf("%d", x);
}