文件处理在c ++ [英] file handling in c++

查看:155
本文介绍了文件处理在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码从文件输入数字,但最后一个数字打印两次,我觉得困惑。什么可能是可能的答案。
提前感谢。

I wrote the following code to input numbers from a file however the last number gets printed twice which I find perplexing. What could be the possible answer. Thanks in advance.

代码:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    int x;
    ifstream f;
    f.open("note");
    while(!f.eof()){
            f>>x;
            cout<<x<<endl;
    }
    return 0;
}

输出:

1
2
3
4
5
5

文件注释的内容是:

1
2
3
4
5 


推荐答案

到目前为止的每个解决方案都有一个很好的解释为什么OP代码是错误的。但大多数都有不正确的解决方案的问题。

Every solution so far presented has a good explanation of why the OP code is wrong. But most have the incorrect solution to the problem.

多次之前,EOF标志没有设置,直到你尝试和阅读超过文件结束。最后一次成功读取可以读取(包括)最后一个字符。所以在你的情况下,最后一次读取将从文件中读取5,然后打印。然后我们进入循环(这将工作,因为最后一次读没有读过去文件的结尾,因此EOF是假的)。您尝试读取下一个字符将失败, f>> x 并且变量'x'将保持不变(在您的代码中,这意味着它的最后一个值为5),然后打印。

As stated many times before the EOF flag is not set until you try and read past the end of file. The last successful read may read up-to (inclusive) the last character. So in your case the last read will read the 5 from the file and then print it. We then renter enter the loop (which will work because the last read did not read past the end of file and thus EOF is false). Your attempt to read the next character will fail at f >> x and the variable 'x' will be left untouched (in your code this means it has the last value read a 5) and is then printed.

解决方案是在您完成读取后测试流的条件,以确保它的工作。注意:你不应该专门测试EOF有其他坏状态。如果输入其他错误状态之一,当前代码将进入无限循环。要检查所有的坏位,调用fail()对象。所以最简单的解决方案是把读入的while测试(见下文)

The solution is to test the condition of the stream after you have done the read to make sure it works. Note: You should not exclusively test for EOF there are other bad states. If one of the other bad states is entered the current code will enter an infinite loop. To check for all bad bits call fail() on the object. So the easiest solution is to put the read into the while test ( see below )

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    int x;
    ifstream f;
    f.open("note");
    while(f>>x)
    {
            cout<<x<<endl;
    }
    return 0;
}

这是因为>>运算符返回流。当一个流对象在布尔上下文中使用时,它被转换为一个类型,可以表示true / false(由于技术原因,这不是bool,但你可以认为它是一个bool)。返回的值取决于流的状态。如果流处于良好状态,则它将(在布尔上下文中)评估为真,因此如果流对象处于无效状态(即,EOF(或其他失败状态)为真)则允许输入循环,则它将评估为false,并且不输入循环。

This works because the >> operator returns a stream. When a stream object is used in a boolean context it is converted into a type than can represent true/false (for technical reasons this is not bool but you can think of it as a bool). The value returned depends on the state of the stream. If the stream is in a good state then it will (in a boolean context) evaluate to true thus allowing the loop to be entered, if the stream object is in an invalid state (ie EOF (or other failed state) is true) then it will evaluate to false and the loop is not entered.

注意:转换实际上在流上调用fail()来测试状态。

Note: The conversion actually calls fail() on the stream to test the state.

如果你的代码很复杂,你不能测试状态作为读的一部分。然后在每次读取之后,必须测试对象的状态以验证其是否有效。

If your code is complex and you can not test the state as part of the read. Then after each read you MUST test the state of the object to verify it worked.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    int x;
    ifstream f;
    f.open("note");
    while(f)
    {
            f>>x;
            if (f) // dont' use f.eof() there are other bad states.
            {      // This will actuall call f.fail() which test for all bad states.
                   // Thus it only prints if the read worked.

                  cout<<x<<endl;
            }
            // Alternatively you can put the read into the if
            if ( f >> x)
            {
                  // STUFF
            }
    }
    return 0;
}

回应Jim的意见。

已从具有>>运算符的流读取。不读取其他字符。要显示这是真的试试下面的代码:

In response to Jim's comments.
Once a number has been read from the stream with the >> operator. No other characters are read. TO show this is true try the following code:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream  file("txt");
    std::string    line;
    int            x;

    while(f >> x)
    {
        std::getline(f, line);   // If the '\n' was read then
                                 // this code would remove the next line.
                                 // As it works correctly it simply removes then
                                 // characters upto the newline character after the number.
        std::cout << x << "\n";
    }
}

这篇关于文件处理在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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