[英]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.
我的首选方法是eof循环。 However, my file has 10 dates, and my output has 30. Here is my main for context.
但是,我的文件有10个日期,输出有30个日期。这是上下文的主要内容。
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. 您似乎正在尝试使用
date
来一次表示三件事。
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. 在这里,你看另外一个号码,并把它传递给
getWeekDay
三次。
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). 您的循环将继续进行,直到没有更多的数字可读取为止(排序:请参见上面的有关
eof
用法的注释),在您的情况下,该过程将花费您预期的三倍时间(即30而不是10),因为您读了三倍的数字您所想的数字(再次参见上文)。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.