简体   繁体   中英

cin buffer not being ignored?

while(cout << "Enter a positive integer: " &&
        (!(cin >> anInteger) || anInteger < 0))
{
    cout << "Enter a positive integer.\n";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

while(cout << "Read or write (r/w): " &&
        (!(cin >> rw) || (rw != 'r' && rw != 'w')))
{
    cout << "Enter r or w.\n";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

Here I ask for an integer, followed by 'r' or 'w'. However, when inputting something like '4r' into the first while statement, the 'r' stays in buffer and is applied to the next while statement. How can I fix this?

What's the easiest way to only accept input if it's ALL integers in the first while loop instead of cutting off characters?

You can just ignore() what's on the line after the integer: when reading an integer the read stops at the first character not fitting an integer, ie, the following newline wouldn't be read.

Considering you are ignoring characters until the end of line in multiple places it may be reasonable to create and use a manipulator to do so:

std::istream& igln(std::istream& in) {
    return in.ignore(std::numeric_limits<std::streamsize>::max());
}
...
while (std::cout << "Read or write (r/w): "
    && (!(std::cin>> igln >> rw) || (rw != 'r' && rw != 'w')) {
    std::cout << "Enter r or w!\n";
    if (std::cin.eof()) {
        throw std::runtime_error("reached end of stream\n");
    }
    std::cin.clear();
}

Note that the loop always ignores the rest of the line and, thus, it isn't needed inside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM