关于 sscanf 的困惑
我想从文件中读取浮点数(以及之后的整数)。当我调试它时,我可以看到它从文件中获取该行没有问题,但是当我尝试 sscanf 它时,我得到了垃圾。这是我的代码:
while(fgets(line, 1000, file) != EOF)
{
//Get the first character of the line
c = line[0];
if(c == 'v')
{
sscanf(line, "%f", &v1);
printf("%f", v1);
}
}
v1 中存储的值是垃圾。为什么这不起作用,如何从这一行中获取浮点数和整数?
I want to read floats (and ints afterwards) from a line I'm getting out of a file. When I'm debugging it, I can see it's getting the line out of the file no problem, but when I try to sscanf it, I'm getting garbage. Here's my code:
while(fgets(line, 1000, file) != EOF)
{
//Get the first character of the line
c = line[0];
if(c == 'v')
{
sscanf(line, "%f", &v1);
printf("%f", v1);
}
}
The value stored in v1 is garbage. Why is this not working, and how can I get floats and ints out of this line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您在对 sscanf 的调用中包含第一个字符(即“v”),因此调用失败,并且
v1
保持不变(其中有垃圾)。试试这个:You're including the first character (which is 'v') in the call to sscanf, so the call is failing and
v1
is left untouched (with garbage in it). Try this instead:大概 v1 是一个浮点数?
在这种情况下,在内存中打印一个浮点,就像它是一个“c”字符串一样,会很糟糕。
您可能想尝试
printf("%f",v1);
如果行以“v”开头,那么您要将其发送到 scanf 并要求它将其转换为浮点数?您可能想要移动一个字符(或者更多,如果您有其他填充),然后开始读取第 [1] 行的浮点数?
Presumably v1 is a float?
In which case printing a float in memory as if it was a 'c' string is going to be bad..
You might want to try
printf("%f",v1);
If line starts with 'v' then you are sending that to scanf and asking it to convert it into a float? You probably want to move on a character (or more if you have other padding) and then start reading the float at line[1]?
您的 printf 语句应该如下所示:
另外,您应该检查 sscanf 的返回值以检查它是否找到并存储了浮点数:
Your printf statement should look like this:
Also, you should check the return value of sscanf to check if it is even finding and storing the float:
由于您知道执行
sscanf()
调用时line
中的第一个字符是字母“v”,因此您还可以知道>sscanf()
可以成功将其转换为double
或float
,因为“v”不是任何以字符串形式呈现的有效浮点数的一部分。您应该检查 sscanf() 的返回值;它会显示 0(没有成功转换),从而告诉您出现了问题。
您可能会成功:
Since you know when you execute the
sscanf()
call that the first character inline
is the letter 'v', you can also tell that there is no way thatsscanf()
can succeed in converting that to adouble
orfloat
because 'v' is not part of any valid floating pointing number presented as a string.You should check the return value from
sscanf()
; it would say 0 (no successful conversions), thereby telling you something has gone wrong.You might succeed with: