Gilian Joosen
Gilian Joosen

Reputation: 486

Sscanf doesn't give me a value

I have this piece of code:

if(string_starts_with(line, "name: ") == 0){
    //6th is the first char of the name
    char name[30];
    int count = 6;
    while(line[count] != '\0'){
        name[count-6] = line[count];
        ++count;
    }
    printf("custom string name: %s", name);
    strncpy(p.name, name, 30);
}
else if(string_starts_with(line, "age: ") == 0){
    //6th is the first char of the name
    printf("age line: %s", line);
    short age = 0;
    sscanf(line, "%d", age);
    printf("custom age: %d\n", age);
}

The if works, but the else if doesn't work. Example output is:

person:
name: great
custom string name: great
age: 6000
age line: age: 6000
custom age: 0

I have changed a lot, like using &age in the sscanf function, but nothing works.

Upvotes: 0

Views: 668

Answers (2)

ameyCU
ameyCU

Reputation: 16607

short age = 0;
sscanf(line, "%d", age);

age is of type short and format specifier you used is %d which is wrong.

Use %hd for short instead-

  sscanf(line+5, "%hd",&age);

Upvotes: 1

rici
rici

Reputation: 241711

If you want to store a value into a short (why¿?) you need to use an appropriate length modifier. Also, if you are expecting the number to come after the prefix string, you need to start the scan after the prefix string. Finally, as you mention in passing, it is necessary to give sscanf the address of the variable in which you want to store the value.

And remember to check the return value of sscanf to make sure you found a number.

In short:

if (sscanf(line + 5, "%hd", &age) != 1) {
  /* handle the error */
}

Several of these errors (but not all of them) would have been shown if you had compiled with extra warnings enabled. With gcc or clang, always use -Wall in your compiler options.

Upvotes: 6

Related Questions