用`scanf()`读取逗号分隔的输入 [英] read comma-separated input with `scanf()`
本文介绍了用`scanf()`读取逗号分隔的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下输入内容:
AG23,VU,Blablublablu,8
IE22,VU,FooBlaFooBlaFoo,3
and so on...
我希望它使用这样的代码与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
}
但是代码的执行给了我:illegal instruction
But the execution of the code gives me: illegal instruction
您将如何读取以逗号分隔的文件?
How would you read a comma-separated 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.
指定宽度可防止缓冲区溢出.
Specifying the width prevents buffer overrun.
这篇关于用`scanf()`读取逗号分隔的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文