Example of Why stream::good is Wrong?

后端 未结 5 646
星月不相逢
星月不相逢 2021-01-02 01:43

I gave an answer which I wanted to check the validity of stream each time through a loop here.

My original code used good and looked similar to this:

5条回答
  •  孤独总比滥情好
    2021-01-02 02:31

    both good() and eof() will both give you an extra line in your code. If you have a blank file and run this:

    std::ifstream foo1("foo1.txt");
    std::string line;
    int lineNum = 1;
    
    std::cout << "foo1.txt Controlled With good():\n";
    while (foo1.good())
    {
        std::getline(foo1, line);
        std::cout << lineNum++ << line << std::endl;
    }
    foo1.close();
    foo1.open("foo1.txt");
    lineNum = 1;
    
    std::cout << "\n\nfoo1.txt Controlled With getline():\n";
    while (std::getline(foo1, line))
    {
        std::cout << line << std::endl;
    }
    

    The output you will get is

    foo1.txt Controlled With good():
    1
    
    foo1.txt Controlled With getline():
    

    This proves that it isn't working correctly since a blank file should never be read. The only way to know that is to use a read condition since the stream will always be good the first time it reads.

提交回复
热议问题