Why I can't flush the input stream properly using std::cin.ignore?

Viewed 53

I've used to clear the input buffer this way:

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

std::cin.clear();

And it works just fine. but now I don't know why this doesn't work?

int main(){

    std::vector<int> v;
    for(int i; std::cin >> i; )
        v.push_back(i);

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

    int x;
    std::cout << "x: ";
    std::cin >> x;
    std::cout << x << '\n';

    std::cout << std::endl;
}

Input: 4 5 7 ^d

Output: x: 0

  • Why I am not prompted to input x? -I've also cleared the stream before calling std::cin.ignore:

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

But the problem persists!

PS: I am using g++ (GCC) 10.3.1 20210422 (Red Hat 10.3.1-1) on fedora 33. and Code::blocks 20.03

  • If I enter a non integer like a character e.g: 'a' it works just fine but if I enter EOF (CTRL+D) it doesn't work!
0 Answers
Related