使用 `scanf()` 读取逗号分隔的输入 [英] read comma-separated input with `scanf()`

查看:35
本文介绍了使用 `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
}

但是代码的执行给了我:非法指令

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屋!

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