Start New Discussion within our Software Development Community

i have a code that reads lowest and the highest number with inputs that are all Integer
but, once i have an input (ex. apple 200)...it wont read anymore, need help in what to input code that ignores letters

//reads numbers only ex. 100 200 300
int main()
{	
	ifstream in;
	ofstream out;
	
	in.open("input.txt");
	if (in.fail())
	{
		cout<<"Unable to open \"Input.txt\"";
		cin.ignore(numeric_limits<streamsize>::max(),'\n');
		cin.get();
		exit(1);
	}
	
	
	int number, lowest=numeric_limits<int>::max(),highest =0;
	in>>number;
	while(!in.eof())
	{
		

		if(number >highest)
		{
			highest=number;
		}
		if(number<lowest)
		{
			lowest =number;
		}
		in>>number;
		
	}
	out<<"Highest is: "<<highest<<endl;
	out<<"Lowest is : "<<lowest<<endl;
		
	in.close();
	out.close();


		cout<<"Done";
	cin.ignore(numeric_limits<streamsize>::max(),'\n');
	cin.get();
	return 0;
}

Quite simply you are reading into an int variable. Therefore once text is read the stream goes into a fail state, which isnt as catastrophic as it seems. All this tells you is that the input encountered something it could not put into an int. A string. To resolve this (make the stream read again at least) use in.clear() .However you may wish to consider reading into a string or stringstream from the file. then checking the input for characters, discarding those and reading only the numbers. Doing some input filtering like this yourself keeps the stream happy and means you still only get what you want.

One final thing

in>>number;
while(!in.eof())//will cause the last character to be read twice

while(in>>number) //will read the last value only once as the check for eof etc is done here so it breaks at the right time

Hope this helps

This article has been dead for over six months. Start a new discussion instead.