Search code examples
c++c++11user-inputiostreamcin

istream loop makes the program jump over cin statement


Here is a program that takes a sequence of space-separated numbers and stores then in a vector. The problem is when putting the cin loop before the input of x0, the program jumps the next cin statement, but the reverse is working very normally.

Can you explain to me what I am missing here?

State of jump:

vector<int> V{};
int x0{}, temp{};
        
cout << "Enter sequence\n";
for(temp;cin>>temp;)
{
    if (!isalpha(temp)) V.push_back(temp);
    else
    {
        cin.clear();
        break;
    }
}
cout<<"enter x0 : ";
cin >> x0;// the program skips this!

The working reverse:

vector<int> V{};
int x0{}, temp{};
cout<<"enter x0 : ";
cin >> x0;
cout << "Enter sequence\n";
for(temp;cin>>temp;)
{
    if (!isalpha(temp)) V.push_back(temp);
    else
    {
        cin.clear();
        break;
    }
}

Solution

  • In the first example, you are calling cin >> temp in a loop until the read fails, either because a non-integer is entered, or the user explicitly ends input (with Ctrl-C or Ctrl-Z or whatever your platform uses). And then you are trying to call cin >> x0 without first clearing cin's error state, so that read will also fail.

    Your call to cin.clear() (which does not discard data in cin's input buffer, only resets cin's error state) needs to be done after operator>> fails, not after the isalpha() check, eg:

    vector<int> V;
    int x0, temp;
            
    cout << "Enter sequence\n";
    do
    {
        if (!(cin >> temp))
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            break;
        }
    
        if (isalpha(temp))
            break;
    
        V.push_back(temp);
    }
    while (true);
    
    cout << "enter x0 : ";
    cin >> x0;
    

    In the second example, you are not trying to call cin >> x0 after a failed read, which is why that code works (provided that the user actually enters a valid integer for cin >> x0, otherwise cin >> temp will fail immediately since you are not resetting the error state or discarding data from the buffer).