阅读scanf函数逗号分隔输入 [英] read comma-separated input with scanf

查看:229
本文介绍了阅读scanf函数逗号分隔输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入:

AG23,VU,Blablublablu,8
IE22,VU,FooBlaFooBlaFoo,3
and so on...

我希望它使用一些code这样的解析与scanf函数:

i want it to "parse" with scanf using some code like this:

char sem[5];
char type[5];
char title[80];
int value;

while(scanf("%s,%s,%s,%d", sem, type, title, &value) == 4) {
 //do something with the read line values
}

不过,code的执行给我: illegale指令
你会如何​​读取逗号分隔的文件中像这样?

But the execution of the code gives me: illegale instruction How would you read a comma-seperated file like this?

推荐答案

逗号不被视为一个空格字符,这样格式说明%S会消耗,一切就行书写超出了数组的边界别的 SEM 导致未定义的行为。要纠正这一点,你需要使用扫描集:

The comma is not considered a whitespace character so the format specifier "%s" will consume the , and everything else on the line writing beyond the bounds of the array sem causing undefined behaviour. To correct this you need to use a scanset:

while (scanf("%4[^,],%4[^,],%79[^,],%d", sem, type, title, &value) == 4)

其中:


  • 4%[^,] 阅读最多四个字符,或直到遇到一个逗号表示。

  • %4[^,] means read at most four characters or until a comma is encountered.

指定宽度prevents缓冲区溢出。

Specifying the width prevents buffer overrun.

这篇关于阅读scanf函数逗号分隔输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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