The example in this post is from C++ Primer Plus (6th Edition) by Stephen Prata

My question: Why cin.ignore( ) is not used in his example? Shouldn't we discard the buffer with a line similliar to this:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Example from the book:

int fill_array(double ar[], int limit)
{
    using namespace std;
    double temp;
    int i;
    for (i = 0; i < limit; i++)
    {
        cout << "Enter value #" << (i + 1) << ": ";
        cin >> temp;
        if (!cin) // bad input
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Bad input; input process terminated.\n";
            Functions and Arrays 327
                break;
        }
        else if (temp < 0) // signal to terminate
            break;
        ar[i] = temp;
    }
    return i;
}

Recommended Answers

All 2 Replies

Shouldn't we discard the buffer with a line similliar to this:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Your line discards the buffer up to and including the '\n'. So does lines 13 and 14. The cin stream failed when the user entered a character that did not make sense for a double. Line 12 reset cin as a good stream. You have whatever you have left over in the stream, including '\n'. cin.get() reads a character from the cin stream and throws it away, just like ignore. When it hits the '\n', it stops, just like ignore. It's the same line, just one character at a time in a loop rather than all at once in the ignore statement.

Thank you, it makes sense now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.