使用fscanf从文件读取字符串,整数等 [英] Reading strings, integers etc from files using fscanf

查看:751
本文介绍了使用fscanf从文件读取字符串,整数等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like your help with understanding how should I do the following:

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

I have a file that contains integers separated by spaces ' '. I need to read all integers, sort them and write them as a strings to another file. I wrote a code, but I read char by char, put the word in an char sub_arr [Max_Int] and when I met ' ', I put these chars, now one string, after atoi-ing it into another Main int array,until reaching the end of the file, string by string, and then I sorted and itoa-ing them and wrote them in another file.

但是后来我想起有一个 fscanf 函数:我读到了有关它,但我仍然不完全了解它的功能以及如何使用它.

But then I remembered that there's a fscanf function:I read about it and still I didn't understand completely what does it do and how to use it.

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

In my case, where all integers separated by space, can I write fscanf(myFile,"%s",word)? would it know not to consider ' ' and stop at the end of the specific string?! How?

不仅如此,我还能写fscanf(myFile,"%d",number),它会给我下一个数字吗? (我一定误会了.感觉​​就像魔术一样.)

More than that, Can I write fscanf(myFile,"%d",number) and it would give me the next number itself? (I must have misunderstood it. Feels like magic).

推荐答案

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

You are right, fscanf can give you the next integer. However, you need to provide it with a pointer. Therefore, you need an & behind number:

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

*scanf系列功能还自动跳过空格(给定%c%[%n时除外).

*scanf family of functions also automatically skip whitespace (except when given %c, %[ or %n).

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

Your loop with reading file will eventually look like this:

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);
}


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


Side note: you may think of writing like this:

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

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

This, although looks nice, has a problem. If you are indeed reaching the end of file, you will have read a garbage number and added to your data before testing the end of file. That is why you should use the while loop I mentioned first.

这篇关于使用fscanf从文件读取字符串,整数等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆