开发者

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. 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?


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:

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


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(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? You probably want to move on a character (or more if you have other padding) and then start reading the float at line[1]?


Your printf statement should look like this:

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

Also, you should check the return value of sscanf to check if it is even finding and storing the float:

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.

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:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜