Reputation: 1
I could use some advice on how to get C++ to only read a set amount of lines from a txt file.
There are 365 lines in the file, and each line contains the number of steps taken during a
day. The first 31 lines are for January, then February and so on. Then I'm supposed to find the average of each month and display it. I'm having trouble trying to get the program to only read the first 31 then move on to the next month. Also I'm new to stack overflow so I apologize for any bad formatting.
int main()
{
int days;
inFile.open("steps.txt"); // open file
if (!inFile)
{
cout << "Failure to open file" << endl;
exit (EXIT_FAILURE);
}
days = jan(1);
}
int jan(int lineR)
{
int sum, i;
while (i != 31)
{
while (inFile >> lineR) // read line by line
{
i++;
cout << lineR << endl;
sum = lineR + sum;
sum = sum / i;
}
}
cout << sum << endl;
return i;
}
Upvotes: 0
Views: 123
Reputation: 51
int main()
{
ifstream inFile;
int sum = 0, lineCounter = 0, monthPointer = 0, x;
inFile.open("steps.txt");
int monthsArray[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (!inFile)
{
std::cout << "Unable to open file";
exit(1);
}
while (inFile >> x)
{
if (lineCounter == monthsArray[monthPointer])
{
// se la riga è arrivata al limite del mese corrente allora stampo
int avg = sum / lineCounter;
std::cout << "Month " << monthPointer + 1 << std::endl;
std::cout << "Avg = " << avg << std::endl;
sum = 0;
lineCounter = 0;
monthPointer++;
}
sum = sum + x;
lineCounter++;
}
inFile.close();
std::cout << "_______" << std::endl;
std::cout << "Sum = " << sum << std::endl;
std::cout << "Line Counter = " << lineCounter << std::endl;
return 0;
}
Upvotes: 0
Reputation: 15446
Instead of
while (inFile >> lineR )// read line by line
You can switch to a for-loop with a counter:
for (int i = 0; inFile >> lineR && i < 31; i++ )
But for readability, magic numbers should be avoided, so I'd actually replace that 31 with a variable:
const int DAYS_IN_MONTH = 31;
for (int i = 0; inFile >> lineR && i < DAYS_IN_MONTH; i++ )
Also, note that inFile >> lineR
isn't actually reading the whole line. It's just reading the next int
it can find (and possibly breaking terribly). To read a full line, you could make a string variable and use std::getline
):
std::string line;
for (int i = 0; std::getline(inFile, line) && i < 31; i++ )
Upvotes: 3