简体   繁体   中英

EOF loop repeats lines 3 times before finally ending

I have an assignment where I'm given a file containing dates in numbered format and I have to have a program read the file and spit out days of the week for each date give. Each line of the file is a separate date. My go-to method was an eof loop. However, my file has 10 dates, and my output has 30. Here is my main for context.

int main()
{
    ifstream inFile;
    inFile.open("/Users/holdentatlow/Desktop/date 2");

    const char *Names[] = {"Sunday","Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};

    int day = 0;

    int date;

    inFile >> date;
    cout << "Day : " << Names[day] << endl;

    while (!inFile.eof()){

        inFile >> date;
        day = getWeekDay(date, date, date);
        cout<< "Day : "<< Names[day] <<endl;

    }

    inFile.close();

    return 0;
}

also, I get the impression that the dates it does report aren't entirely accurate. I don't have the resolve to check each one individually but the results seem erratic enough to not be simply repeated.

here's the file I'm taking dates from

0 10  1900
2 16 1900
1 2 1944
0 1 2004
1 29 2004
11 24 2002
6 2 2050
2 23 2004
0 6 1812
1 3 1800

You seem to be trying to use date to mean three things at once.

int date;
inFile >> date;

Here you read one number. One. Not three; one .

while (!inFile.eof()){

Here you commit a cardinal sin; that is not how to loop over input .

inFile >> date;
day = getWeekDay(date, date, date);

Here you read another one number, and pass it to getWeekDay three times.

Your loop continues until there are no more numbers to read (sort of: see note above about that eof usage), which in your case will take three times as long as you expected (ie 30 not 10) because you read a third as many numbers as you thought (again, see above).

You'll want an >> operation for each number you want to read.

Here's an improved version of your program:

#include <fstream>
#include <istream>
#include <iostream>

// Assumed defined elsewhere
int getWeekDay(int date, int month, int year);

int main()
{
    std::ifstream inFile("/Users/holdentatlow/Desktop/date 2");

    static const char* Names[] = {
       "Sunday",
       "Monday",
       "Tuesday",
       "Wednesday",
       "Thursday",
       "Friday",
       "Saturday"
    };

    int date, month, year;
    while (inFile >> date >> month >> year) {
       const int day = getWeekDay(date, month, year);
       std::cout << "Day : " << Names[day] << std::endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM