3

I'm having troubles with sscanf() function to read doubles. I have a comma separated text file like this:

ABC,DEF,0.465798,0.754314
GHI,JKL,0.784613,0.135264
MNO,OPQ,0.489614,0.745812
etc.

So first I get the line with fgets() and then I use sscanf() to get the two string and two double variables.

fgets(buffer, 28, file);
sscanf(buffer, "%4[^,],%4[^,],%lf[^,],%lf[^\n]", string1, string2, &double1, &double2);

printf("%s %s %f %f\n", string1, string2, double1, double2);

But the output is:

ABC DEF 0.465798 0.000000
GHI JKL 0.784613 0.000000
MNO OPQ 0.489614 0.000000

So somehow it doesn't scan the last float. I've tried %lf[^ \t\n\r\v\f,] and just %lf but it still doesn't work.

4

4 回答 4

3

除非您的变量double1double2是指针,否则您将获得未定义的行为。

您需要使用 address-of 运算符&来获取指向这些变量的指针:

sscanf(buffer, "%3s,%3s,%lf,%lf", string1, string2, &double1, &double2);
于 2013-07-31T12:17:18.513 回答
3

改变

"%4[^,],%4[^,],%lf[^,],%lf[^\n]"

int result;
result = sscanf(buffer, "%4[^,],%4[^,],%lf,%lf", string1, string2, &double1, &double2);
if (result != 4) // handle error

注意&ondouble1double2- 很可能是一个错字。

强烈建议检查结果是否为 4。不检查sscanf()结果确实是这个问题的核心。打印出的“零”是double2没有被扫描并保留其先前值的结果,这可能是任何东西。如果sscanf()检查结果,它会报告 3,表明问题在扫描double1double2. 但在更大的场景中,最好在继续之前验证所有预期值都已扫描。

于 2013-07-31T12:17:51.890 回答
2
sscanf(buffer, "%4[^,],%4[^,],%lf[^,],%lf[^\n]", string1, string2, double1, double2);

应该

sscanf(buffer, "%3s,%3s,%lf,%lf", string1, string2, &double1, &double2);

双打的备注&(地址)

于 2013-07-31T12:16:08.947 回答
1

您的代码不起作用的原因是:

sscanf(buffer, "%4[^,],%4[^,],%lf[^,],%lf[^\n]", string1, string2, &double1, &double2);

%[...]并且%[^...]实际上是转换类型,例如%d, %x,它们匹配/不匹配列出的字符序列,以 . 结尾]。请注意,您不必提供%s,即使您正在解析字符串。

您的问题是您结合了两种类型的转换类型,%lf并且[^...]scanf 实际上将后面的部分视为要匹配的字符串,因此例如以下代码将成功解析字符串:

char *b = "ABC,DEF,0.465798[^,],0.754314[^\n]\n";
sscanf(b, "%4[^,],%4[^,],%lf[^,],%lf[^\n]", string1, string2, &double1, &double2);

最简单的解决方案是留下[^,]部分(chux 的解决方案):

sscanf(b, "%4[^,],%4[^,],%lf,%lf", string1, string2, &double1, &double2);

或使用字段宽度(Joachim Pileborg 和 David RF 的解决方案):

sscanf(buffer, "%3s,%3s,%lf,%lf", string1, string2, &double1, &double2);
于 2013-07-31T12:37:23.970 回答