tenkii
tenkii

Reputation: 449

scanf() not returning the correct number of arguments

I am trying to write a simple program that will take input about people in this format:

 name,age,gender,info

Here is the code so far:

 #include <stdio.h>

 int main() {
    char name[10];
    int age;
    char gender[2];
    char info[50];

    while(scanf("%9s,%i,%1s,%49[^\n]", name, &age, gender, info) == 4)
    puts("Success");

    return 0;
 }

So at the terminal I enter something like: bob,10,M,likes cheese but it does not print out the success message, so I guess the condition at the while loop failed.

So add this code to check the number of arguments:

int i = scanf("%9s,%i,%1s,%49[^\n]", name, &age, gender, info);
printf("%i", i);

and when I enter bob,10,M,likes cheese again, it prints out 1.

Can anyone help please?

Upvotes: 1

Views: 180

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55619

%9s will consume input until it finds white-space, reaches the specified length (9) or the end of the string, which, in this case, will consume bob,10,M, instead of just bob.

Test.

Try %9[^,],%i,%1s,%49[^\n] instead.

Test.

Also, since gender is 1 character, you may as well make it a char and use %c instead of %1s (unless it's optional).

Test.

Upvotes: 4

Related Questions