6
votes

I'm trying to get a very large number (more than unsigned long long int). So I get it as a string and then convert it, digit by digit, into integer and use it.

#include <stdio.h>
#include <string.h>

int main() 
{ 
    char m[100];
    int x;
    scanf("%s",m);
    for(int i=0; i<strlen(m); i++){
        sscanf(m[i],"%d",&x);
        printf("%d",x);
    }

    return 0; 
}

However, during compiling it shows:

warning: passing argument 1 of ‘sscanf’ makes pointer from integer without a cast

and

note: expected ‘const char * restrict’ but argument is of type ‘char’

And, when I run program it will give me the Segmentation fault (core dumped) error.

I also tried more simple code to find the problem:

#include <stdio.h>
#include <string.h>

int main() 
{ 
    char m[5];
    char n;
    int x;
    scanf("%s",m);
    n = m[1];
    sscanf(n,"%d",&x);  
    return 0; 
}

but nothing changed.

3
%d does not mean "digit" it means "signed decimal integer". But as to the error itself, sscanf needs a const char * (ie a string) but you have given a single character.kaylum
With m being only four characters plus a thanks, ”very long” is an appalling misnomer. You can't safely use %d for really long strings of digits; the behaviour on overflow is undefined.Jonathan Leffler
sscanf(m[i],"%d",&x); is wrong. You should do x = m[i] - '0'; instead. and your input string is too small for a big number.Jean-François Fabre

3 Answers

4
votes

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) {
2
votes

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;
}
2
votes

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);
}