Write a c++ program that will count the numbers of players in the footballstats.txt file and determine the biggest and smallest player numbers. The program is to use the datain.fail function to read the numbers. The program is output the results to the monitor.
Can anyone redirect me to a good example of this datain.fail function?
If there are just two columns of integers, then all you have to do is read the data in pairs.I'll leave it to you to choose more appropriate names than just a and b.
1 2 3
int a;
int b;
datain >> a >> b;
Then, after each successful read from the file, add 1 to a count variable.
#include <iostream>
#include <fstream>
usingnamespace std;
ifstream datain("footballstats.txt");
int main (){
int num, weight ;
while (true)
{
datain >> num >> weight;
if (datain.fail())
break;
cout <<"player number weight" << endl; // I'm lost if I'm even doing this right..
}
system("PAUSE");
return 0;
}
Does not read the numbers, reads the amount but doesn't input the numbers..
The above code seems to just print out the heading line repeatedly. If you don't get that far, then the file has not been opened successfully. If you want to see the other details displayed, modify the cout statement accordingly.
You can check for file being open by testing the fail() status before the start of the while loop.
By the way, there's no reason to place the ifstream in the global scope outside of main(). Generally global variables are considered bad practice.
What output do you get? What happens when you run it?
There are a number of errors which might or definitely will cause problems.
Lines 14-15 if (datain.fail()) are out of sequence. You should perform the file access first, then test whether or not it was successful.
line 16 datain >> num[count] >> weight[count++]; can give undefined behaviour since the variable count is used more than once in the same line and is also changed. The compiler is not obliged to carry out the update of count at any particular stage, results are unpredictable.
You should move the count++ to a separate line, after the input operation, and indeed after the fail() has been checked. There's no point in adding 1 to indicate something was read from the file unless the input succeeded.
Line 24 --count this is not necessary, it was only added because of errors earlier in the code.