jeudi 5 octobre 2017

Why does std::istream::ignore not return when called on an empty stream?

std::cin is a global object, and as such I always want to set it to a good state before using it. However, when invoking ignore() on an unused cin the function doesn't return.

See sample code below. Execution doesn't reach line 8 (cout) without user intervention. In my testing this behavior is consistent with or without the second argument (the delimiter, I've tried '\n' and EOF).

I've been through a couple of online references, but I don't see why this happens.

#include <limits>
#include <iostream>
#include <string>
std::string readInput() {
    std::string input = "";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "We never get here..." << std::endl;
    std::getline(std::cin, input);
    return input;
}
int main() {    
    std::string foo = readInput();  
}

  1. Why does ignore() not return in this case?
  2. How can I safely reset and empty std::cin before use?

Aucun commentaire:

Enregistrer un commentaire