Input not cleared.

Posted by SoulBeaver on Stack Overflow See other posts from Stack Overflow or by SoulBeaver
Published on 2010-04-25T12:08:32Z Indexed on 2010/04/25 12:13 UTC
Read the original article Hit count: 327

Filed under:
|
|

As the question says, for some reason my program is not flushing the input or using my variables in ways that I cannot identify at the moment. This is for a homework project that I've gone beyond what I had to do for it, now I just want the program to actually work :P

Details to make the finding easier:

The program executes flawlessly on the first run through. All throws work, only the proper values( n > 0 ) are accepted and turned into binary.

As soon as I enter my terminate input, the program goes into a loop and only asks for the termiante again like so:

When I run this program on Netbeans on my Linux Laptop, the program crashes after I input the terminate value. On Visual C++ on Windows it goes into the loop like just described.

In the code I have tried to clear every stream and initialze every variable new as the program restarts, but to no avail. I just can't see my mistake.

I believe the error to lie in either the main function:

int main( void )
{
vector<int> store;
int terminate = 1;

do
{
    int    num   =  0;
    string input = "";

    if( cin.fail() )
    {
        cin.clear();
        cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    }

    cout << "Please enter a natural number." << endl;
    readLine( input, num );

    cout << "\nThank you. Number is being processed..." << endl;
    workNum( num, store );

    line;
    cout << "Go again? 0 to terminate." << endl;
    cin >> terminate // No checking yet, just want it to work!

    cin.clear();
}while( terminate );

cin.get();
return 0;
}

or in the function that reads the number:

void readLine( string &input, int &num )
{
    int buf = 1;
    stringstream ss;
    vec_sz size;

    if( ss.fail() )
 {
        ss.clear();
     ss.ignore( numeric_limits<streamsize>::max(), '\n' );
 }

    if( getline( cin, input ) )
    {
       size = input.size();
       for( int loop = 0; loop < size; ++loop )
           if( isalpha( input[loop] ) )
               throw domain_error( "Invalid Input." );

    ss << input;
    ss >> buf;

    if( buf <= 0 )
        throw domain_error( "Invalid Input." );

    num = buf;

    ss.clear();
    }
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about input