使用fscanf从文件中读取字符串,整数等

时间:2012-07-18 14:10:19

标签: c string integer scanf

我希望您能帮助我了解如何执行以下操作:

我有一个包含以空格''分隔的整数的文件。我需要读取所有整数,对它们进行排序并将它们作为字符串写入另一个文件。我写了一个代码,但是我通过char读取char,把这个单词放在char sub_arr [Max_Int]中,当我遇到''时,我将这些字符放入另一个Main int数组后,现在放入一个字符串,直到到达文件的末尾,逐个字符串,然后我对它们进行排序并将它们写在另一个文件中。

但后来我记得有一个fscanf函数:我读过它并且我仍然不完全理解它是做什么以及如何使用它。

在我的情况下,所有整数都用空格分隔,我可以写fscanf(myFile,"%s",word)吗?它会不会考虑''并停在特定字符串的末尾?!怎么样?

更重要的是,我可以写fscanf(myFile,"%d",number)并且它会给我下一个号码吗? (我一定是误解了。感觉像魔术一样。)

3 个答案:

答案 0 :(得分:5)

你是对的,fscanf可以给你下一个整数。但是,您需要为其提供指针。因此,您需要&后面的数字:

fscanf(myFile, "%d", &number);

*scanf系列函数也会自动跳过空格(除非给定%c%[%n)。

您的阅读文件循环最终将如下所示:

while (you_have_space_in_your_array_or_whatever)
{
    int number;
    if (fscanf(myFile, "%d", &number) != 1)
        break;        // file finished or there was an error
    add_to_your_array(number);
}

旁注:您可能会想到这样写:

while (!feof(myFile))
{
    int number;
    fscanf(myFile, "%d", &number);
    add_to_your_array(number);
}

这虽然看起来不错,但有问题。如果您确实到达文件末尾,则在测试文件结尾之前,您将读取垃圾编号并添加到数据中。这就是为什么你应该使用我先提到的while循环。

答案 1 :(得分:2)

以下行将完成您的工作,以下行将读取单个整数。

int number;
fscanf(myFile, " %d", &number);

将其置于循环中直到文件结尾,并将数字放在数组中。

答案 2 :(得分:2)

试试这个:

#include <stdio.h>


int main(int argc, char* argv[])
{
    char name[256];
    int age;
    /* create a text file */
    FILE *f = fopen("test.txt", "w");
    fprintf(f, "Josh 25 years old\n");
    fclose(f);

    /* now open it and read it */
    f = fopen("test.txt", "r");

    if (fscanf(f, "%s %d", name, &age) !=2)
        ; /* Couln't read name and age */
    printf("Name: %s, Age %d\n", name, age);

}
相关问题