c - fscanf() 读取带格式行空格的字符串

标签 c scanf

使用这个结构:

typedef struct sProduct{
  int code;
  char description[40];
  int price;
};

我想读取一个这种格式的txt文件:

1,Vino Malbec,12

格式为:code,description,price。但是当它有空格时我无法阅读描述。

我试过这个:

fscanf(file,"%d,%[^\n],%d\n",&p.code,&p.description,&p.price);

代码保存正常,但随后在描述中保存了 Vino Malbec,12,而我只想保存 Vino Malbec 因为 12 是价格。

有什么帮助吗? 谢谢!

最佳答案

主要问题是 "%[^\n],""%[^\n]"扫描除了'\n'之外的所有内容,所以description扫描了', '。遇到逗号时,代码需要停止扫描到 description

对于面向行的文件数据,第一次读取 1 行。

char buf[100];
if (fgets(buf, sizeof buf, file) == NULL) Handle_EOForIOError();

然后扫描它。使用 %39[^,] 不扫描 ',' 并将宽度限制为 39 个 char

int cnt = sscanf(buf,"%d , %39[^,],%d", &p.code, p.description, &p.price);
if (cnt != 3) Handle_IllFormattedData();

另一个巧妙的技巧是:使用"%n" 来记录解析的结束。

int n = 0;
sscanf(buf,"%d , %39[^,],%d %n", &p.code, p.description, &p.price, &n);
if (n == 0 || buf[n]) Handle_IllFormattedData_or_ExtraData();

[编辑]

简化:@user3386109

更正:@cool-guy删除 &

关于c - fscanf() 读取带格式行空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28711285/

相关文章:

c - 设备驱动程序 Hello world 的 make 文件出错

c - 如何迭代Unicode字符? (不是代码点)

c - 如何添加仅允许 a-f || 之间的字母的 "(if)"A-F?

c - 从文件读取时遇到问题

c - 我将如何使用 fread() 进行部分读取,并在此处获得预期的输出?

c - 位操作 :print the next smallest and largest numbers with same no of 1 bits

c - 在 void* 函数中返回 float

c - 如何从结构中的结构指针访问数据

使用指针更改结构内的数据

c - fscanf() 在不同机器上的行为不同