user2054823
user2054823

Reputation: 23

Why won't this while loop stop?

I can't understand why this while loop isn't stopping once the end condition is matched?

The idea is the user inputs a 5 digit integer and can type anything else to terminate the input process. But

bool noerror(true);
int n(0),part2temp;
vector<int> part2;

while(noerror){
    cout << "Please enter the 5 integer (x to stop)" << endl;
    cin >> part2temp;
    part2.push_back(part2temp);
    n++;

    if (cin.fail()||part2temp>99999||part2temp<10000){
        cout << "End condition matched" << endl;
        cin.clear();
        cin.ignore(10);
        noerror=(false);
    }
}
cout << "escaped loop" << part2[n] << endl;

I get the output to the screen from the IF part of the loop when I type in x for example but for some reason changing the bool value does not terminate the loop and the text "escaped loop" is never shown on screen.

Can anyone tell me what I'm doing wrong?

Upvotes: 0

Views: 887

Answers (3)

fb-np1810
fb-np1810

Reputation: 33

Change

cin.ignore(10);

to

cin.ignore(10,'\n');

then the loop exits, try it!

Upvotes: 0

James Kanze
James Kanze

Reputation: 153899

Why are you using cin.ignore()? As written, cin.ignore() will only return after having read 10 characters. Do you really want the user to have to enter 10 characters after the input (before he enters a new line)? If your input is line oriented, the usual procedure is to use std::getline to read the entire line, then parse it using std::istringstream; alternatively, you can use something like std::cin.ignore( MAX_INT, '\n' );, which will ignore up to the next new line.

Upvotes: 2

hmjd
hmjd

Reputation: 121961

There is undefined behaviour as the part2[n] is going one beyond the bounds of the vector, and may be the reason the output of the following line of code never appears:

cout << "escaped loop" << part2[n] << endl;

giving the impression the loop does not exit. If the loop executes just once then n == 1 and there will be one element only in the vector named part2, which means only part2[0] is valid. To confirm this use vector::at() and wrap it in a try{}catch(std::out_of_range&) block:

try
{
    cout << "escaped loop" << part2.at(n) << endl;
}
catch (std::out_of_range const&)
{
    std::cerr << "Access out of range\n";
}

To correct, confirm the vector is not empty() and use either [n - 1] or vector.back().

Upvotes: 3

Related Questions