我有以下输入:
AG23,VU,Blablublablu,8
IE22,VU,FooBlaFooBlaFoo,3
and so on...
我希望它使用 scanf()
使用如下代码进行“解析”:
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
}
但是代码的执行给了我:非法指令
您将如何读取这样的逗号分隔文件?
最佳答案
逗号不被视为空白字符,因此格式说明符 "%s"
将消耗 ,
以及行上超出数组范围的所有其他内容sem
导致未定义的行为。要纠正这个问题,您需要使用扫描集:
while (scanf("%4[^,],%4[^,],%79[^,],%d", sem, type, title, &value) == 4)
地点:
%4[^,]
表示最多读取四个字符或直到遇到逗号。
指定宽度可防止缓冲区溢出。
关于c - 读取逗号分隔的输入 `scanf()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52908651/