简体   繁体   English

C fscanf问题

[英]C fscanf problem

If I open a file and use fscanf to read a file like this: 如果打开文件并使用fscanf读取文件,如下所示:

2 41 2 41
1 50 1 50
1 46 1 46
.... ....

How do I tell C to read the first number and store it as a variable, then the second as another variable, run a loop, then move on to the next set? 我如何告诉C读取第一个数字并将其存储为变量,然后将第二个存储为另一个变量,运行循环,然后移至下一组?

Some pointers about fscanf : 有关fscanf一些指针:

  1. Always check the return value. 始终检查返回值。 If you asked for one integer, it should return 1 if it scanned successfully. 如果要求输入一个整数,则如果扫描成功,它将返回1 Other return values include 0 or EOF , which may indicate a failure in reading, or a failure in finding data matching the provided pattern. 其他返回值包括0EOF ,这可能表示读取失败或查找与提供的模式匹配的数据失败。

  2. Whitespace characters are usually ignored unless the format specification includes an [ , c or n specifier. 除非格式说明中包含[cn说明符,否则通常会忽略空格字符。

  3. Always check the return value. 始终检查返回值。


while(1)
{
    int result;
    int firstNumber;
    int secondNumber;

    result = fscanf (file, "%d%d", &firstNumber, &secondNumber);
    if (result == 2)
    {
        printf("Scanned two numbers, %d and %d\n", firstNumber, secondNumber);
    }
    else
    {
        if (result != EOF)
            puts("An error occurred");
        break;
    }
}

A loop like this is what you're after: 您所追求的是这样的循环:

int type, stories;

while (fscanf(buildingFile, "%d %d", &type, &stories) == 2)
{
    printf("Got type=%d, stories=%d\n", type, stories);
    /* Do something with 'type' and 'stories' */
}

if (ferror(buildingFile))
{
    perror("buildingFile");
}

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

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