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 <iostream>
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;
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

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.

Edited 5 Years Ago by Fbody: n/a

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