I need to compute the number of nonnegative numbers from an input file. Everything works fine (for good input files and bad input files) except when there is a no data file (with nothing in it). Then, the number of nonneg numbers reads 1, even though it should be 0. Any ideas on how to fix the code?

// Program SumNums reads and counts nonnegative integers until
// the end of file is reached on file SumNums.txt

#include <iostream>
#include <cctype>
#include <fstream>
#include <string>
using namespace std ;

int main ()
{
    ifstream  	data;
    int  	number;	// input value
    int  	count = 0;		// number of positive values
    string	File_Name; 	

    cout <<"Enter file name: " ;
    cin >> File_Name;
    data.open(File_Name.c_str());

	if (data.fail())			
		cout << "Bad input file." << endl << "Program stopped." << endl; 
	else
	{
		while (!data.eof())
		{
			data >> number;
			if (number >= 0)
				count = count++;
		}
    cout  << "The number of nonnegative integers is " << count  << endl;
	}
	
    return 0;
}

Recommended Answers

All 4 Replies

while (!file.eof()) is a bad solution. Remember that ifstream returns 0 when it can't read desired variable from file.
Your "number" is a random number, because if your file is empty you don't write anything into it.

while (!file.eof()) is a bad solution. Remember that ifstream returns 0 when it can't read desired variable from file.
Your "number" is a random number, because if your file is empty you don't write anything into it.

while (!file.eof()) is what my professor taught and expected us to use. How would you fix it, using while (!file.eof()) or something new entirely?

dirty way : number>0
better (imo) way: while(file>>number){if ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.