1

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?

4

1 回答 1

4

%9s将消耗输入,直到它找到空白,达到指定的长度(9)或字符串的结尾,在这种情况下,它将消耗bob,10,M,而不是仅仅bob.

测试

试试%9[^,],%i,%1s,%49[^\n]吧。

测试

此外,由于性别是 1 个字符,您也可以将其设为 achar并使用%c代替%1s(除非它是可选的)。

测试

于 2013-06-09T13:24:03.740 回答