user3444650 user3444650 - 1 month ago 17
C++ Question

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?

Answer

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, i.e., 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.