Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
int count, choice;
int num, sum;
count = 0;
inFile.open("pa5.numbers.cpp");
// if (inFile.fail())
// {
// cout << "Error Opening input file pa5.numbers! \n";
// system("pause");
// return 0;
// }
do
{
cout << "1 - Count Negatives" << endl;
cout << "2 - Average Non-negatives" << endl;
cout << "3 - Sum Numbers" << endl;
cout << "4 - Quit" << endl;
cin >> choice;
if(choice == 1)
{
inFile >> num;
while (!inFile.eof())
{
if(num < 0)
count++;
inFile >> num;
cout << count << endl;
}
}
inFile.close();
inFile.clear();
}while(choice !=4);
system("Pause");
inFile.close();
return 0;
}
The reason it is pa5.numbers.cpp is because i'm running it in devC++ and it keeps the file extension.
I printed out the input file variable num, and it loops "67" over and over again. It is not getting past the first 2 numbers in the input file because they are not negative. Since the if statement seems false, the count++ also isn't counting. I know it is reading my input file, but I can't find why.. anyone?
I took out the else statement inside my if statement and also took out the "if(inFile.fail()" statement to see if that was the cause of the infinite loop but its still doing it..
And to answer your question, yes my teacher did tell me to put "while(!inFile.eof())" to start it off? What is the proper way to read an input file from a while statement?