在C中使用scanf进行解析 [英] parsing using scanf in C

查看:130
本文介绍了在C中使用scanf进行解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次学习C.

我有一个指向名为goalie_stat的字符串的指针(请参见下文).我将如何使用scanf解析保存百分比(即933),然后将933分配给变量,然后最终将其打印出来?

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'是字符串的第13、14和15个字符,但我知道这是不正确的

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

推荐答案

您应该使用sscanf解析字符串,而不是scanf:

You should use sscanf for parsing strings, not scanf:

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

应该可以解决问题! %*s读取并丢弃goalie_stat的第一个单词,第二个%*s读取并丢弃下一个单词(2.28). %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.

您还应该检查sscanf的返回值,看是否成功.

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

这篇关于在C中使用scanf进行解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆