.eof() loop not working

后端 未结 2 1510
既然无缘
既然无缘 2020-12-10 22:29

I\'m trying to read in numbers from a file and putting them into an array. Right now when I run the program it prints 8 numbers, then the line ends and prints the same 8 nu

2条回答
  •  粉色の甜心
    2020-12-10 23:18

    I don't know what your file contains or how it would cause an infinite loop printing more than the last number. However, the eof() bit is only good for error reporting but not for loop control. Also, there is a lot of other stuff in the code which is utterly unnecessary. The following program should read the numbers OK:

    #include                                                              
    #include                                                               
    
    int main()                                                                      
    {                                                                               
        std::ifstream infile("euler8Nums.txt");
        for (int num; infile >> num; )
            std::cout << num << "\n";
        return 0;
    }
    

    I never saw a point in calling open() separately unless there is a conditional necessary necessary before the file name can be worked out. Likewise, calling close() explicitly seems to be pretty pointless unless you want to check that the close was successful (although I'm unsure if close() on an input stream has an opportunity to fail).

    Another of my pet peeves is the unnecessary use of std::endl: this manipulator is a relatively frequent source of bad performance! It does two things:

    1. It writes an end of line character, i.e. \n (or, on wide character streams the result of widening this character).
    2. It flushes the stream. On file streams this is a rather expensive operation which can easily slow down be a substantial factor (not just a few percent). The actual writes often dominate the actual real-time performances of code writing a data to a file.

    Only flush the stream when you really mean to. If you feel that you need extra flushes on your stream, e.g. when trying to find what is written right before a crash, just set std::unitbuf on the stream object: this will be worse from a performance point of view because it flushes the stream after each insertion but it is easily removed once the problem is located.

    Of course, the resulting program can be changed to something even neater like

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::copy(std::istream_iterator(std::ifstream("euler8Nums.txt") >> std::ws),
                  std::istream_iterator(), std::ostream_iterator(std::cout, "\n"));
    }
    

提交回复
热议问题