简体   繁体   English

关于sscanf的困惑

[英]Confusion about sscanf

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. 当我调试它时,我可以看到它从文件中删除线条没有问题,但是当我尝试sscanf它时,我会得到垃圾。 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. 存储在v1中的值是垃圾。 Why is this not working, and how can I get floats and ints out of this line? 为什么这不起作用,我如何从这一行中获得浮动和整数?

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). 你在sscanf的调用中包含了第一个字符(即'v'),因此调用失败并且v1保持不变(其中包含垃圾)。 Try this instead: 试试这个:

sscanf(line+1, "%f", &v1);

Presumably v1 is a float? 据推测v1是浮动?

In which case printing a float in memory as if it was a 'c' string is going to be bad.. 在这种情况下,在内存中打印一个浮点就好像它是一个'c'字符串将是坏的..
You might want to try printf("%f",v1); 您可能想尝试printf("%f",v1);

    if(c == 'v')
    {
        sscanf(line, "%f", &v1);

If line starts with 'v' then you are sending that to scanf and asking it to convert it into a float? 如果行以'v'开头,那么你将它发送给scanf并要求它将其转换为浮点数? You probably want to move on a character (or more if you have other padding) and then start reading the float at line[1]? 你可能想要移动一个角色(如果你有其他填充,或者更多,然后开始在第[1]行读取浮点数)?

Your printf statement should look like this: 您的printf语句应如下所示:

printf("%f\n", v1);

Also, you should check the return value of sscanf to check if it is even finding and storing the float: 此外,您应该检查sscanf的返回值,以检查它是否找到并存储浮点数:

if(sscanf(line, "%f", &v1) < 1){
    /* didn't read float */
}else{
    printf("%f\n", v1);
}

Since you know when you execute the sscanf() call that the first character in line is the letter 'v', you can also tell that there is no way that sscanf() can succeed in converting that to a double or float because 'v' is not part of any valid floating pointing number presented as a string. 既然你知道当你执行sscanf()调用的第一个字符line是字母“V”,你也可以告诉大家,有没有办法sscanf()可以转换,为一个成功的doublefloat ,因为“V '不是以字符串形式显示的任何有效浮点数的一部分。

You should check the return value from sscanf() ; 你应该检查sscanf()的返回值; it would say 0 (no successful conversions), thereby telling you something has gone wrong. 它会说0(没有成功的转换),从而告诉你出了问题。

You might succeed with: 你可能成功:

if (sscanf(line+1, "%f", &v1) != 1)
    ...error...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM