954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ no fail state with entering non integer

Need a little help,
I'm trying to run a program that asks the user to enter an integer between 1-50.
If given a number between 1 and 50 then echo number then add all integer between 1 and integer entered
if user enter an integer not between 1 and 50 then just echo the number and ask the user for another number
if a noninteger is enter i need the program not to go into and fail state, instead clear the noninteger and ask the user for another integer.
To exit the loop you must press cntl-Z.
This is what I have so far: (please help, thanks)

#include
using namespace std;

int main ( )
{
int number;// the integer entered
int sum =0; // the sum of numbers added
int rep = 0;

while(rep != 1)
{
cout << " Enter a positive integer (use cntl-Z to quit)" << endl;
cin >> number;

cout << " " << number << endl;

if (cin.fail())
{
cout << "Bad input, please enter another positive integer (use cnt-Z to quit)" << endl;
cin >> number;
return 0;
}

if ( number >= 1 && number <=50)//test expression
{
for(int i=1;i<=number;i++)
{
sum = sum + i;
}
cout<<"Sum is: "<< sum;
}
}

return 0;
}

helpplease234
Newbie Poster
1 post since Apr 2011
Reputation Points: 10
Solved Threads: 0
 
if (cin.fail())
{
cout << "Bad input, please enter another positive integer (use cnt-Z to quit)" << endl;
cin >> number;
return 0;
}

To start, this is an if, not a function. That return terminates your program. You'll have to get rid of it.

Once you've corrected that, look up the istream::ignore() function , the ios::clear() function , and read this thread . You'll also have to modify the structure of your loops.

Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: