parsing using scanf in C

2019-07-15 05:07发布

I am learning C for the first time.

I have a pointer to a string called goalie_stat (see below). How would i use scanf to parse the save percentage, which is 933 and then assign 933 to a variable and then finally print it?

char *goalie_stat = "PatRoy 2.28  933  35  12  165 199  4   5500"

char save_p = scanf("%[13-15]", goalie_stat);
printf("%s", save_p);

'933' are the 13th, 14th and 15th characters of the string, but i know that this is incorrect

2条回答
来,给爷笑一个
2楼-- · 2019-07-15 05:41

You should use sscanf(). Its utilisation is described here:

http://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-15 05:48

You should use sscanf for parsing strings, not scanf:

int num;
sscanf(goalie_stat, "%*s %*s %d", &num);
printf("%d", num);

should do the trick! %*s reads and discards the first word of goalie_stat and the second %*s reads and discards the next word(2.28). %d then reads the third number and stores it in num.

You should also check the return value of sscanf to see if it was successful.

查看更多
登录 后发表回答