PDA

View Full Version : need sugestions


dugindog
10-19-2005, 09:03 PM
again yes this is homework, the objective is basically exactly what I am doing, however I want to take it 1 step further.

the code is functional for the assignment, however I am looking at a error that is occuring with it (only if I enter a non-integer number / decmial) it seems to go into a funky loop. the assignment only requires integers, however I am not satisfied with that, could someone please take a look at the code and possibly explain why it does that, I'm assuming that is is because of the variable type (int), if someone could give a sugestion for it I would be greatly appreciative.

thanks


#include "stdafx.h"
#include<iostream>

using namespace std;


int main(int argc, char* argv[])
{
int num1;

while( num1 != 0 )
{
std::cout << "Enter An Integer: " << std::endl;
std::cin >> num1;
if (num1 > 0)
std::cout << "The number is Positive." << std::endl;
if (num1 < 0)
std::cout << "The number is Negative." << std::endl;
}
return 0;
}

sage45
10-19-2005, 11:12 PM
Has to do with the fact the the iostream enters an error state when the iostream is false... Meaning quite sipmly the the iostream was expecting an integer value and recieved a non-integer value, namely a non-numeric value as a float or double will be truncated to an integer value...

There is a simple way to fix this...#include<iostream>

using namespace std;

int main(int argc, char* argv[])
{
int num1;

while( num1 != 0 )
{
cout << "Enter An Integer: " << endl;
cin >> num1;
// If input stream is false.
if (!cin)
{
// Clear input stream.
cin.clear();
cin.ignore(100, '\n');

// Output error message to screen.
cout << "Invalid option. Please try again." << endl;
}
else
{
if (num1 > 0)
cout << "The number is Positive." << endl;
if (num1 < 0)
cout << "The number is Negative." << endl;
}
}
return 0;
}HTH,

-sage-

oracleguy
10-20-2005, 12:23 AM
And another implementation of the same idea:


cout << "Enter the number in: ";
while(!(cin >> num1))
{
cin.clear(); //Clear any error flags
cout << "Invalid input, please try again.\nEnter the number in: ";
cin.ignore(cin.rdbuf()->in_avail());
}

dugindog
10-20-2005, 03:42 PM
I am glad to have found the forums here, everyone seems to be very helpful.

thank you all.

mashekle
10-27-2005, 10:04 AM
Just wanted to say "Thank you VERY much for posting this fix!" :thumbsup: