How to continue using cin.getline after the user has entered ^D

Viewed 34

How to continue using cin.getline() after the user has entered ^D?

In the following code, if you type ^D in the first input, all subsequent calls to getline() will get eof. So, how do you get getline() to continue to work?

#include <iostream>
#include <string>

int main ()
{
  std::string cmd;

  std::cout << "Enter u name or press ^D: ";
  std::getline (std::cin, cmd);
  std::cout << "Hello, " << cmd << "!\n";
  std::getline (std::cin, cmd);
  if (std::cin.eof()) {
      std::cout << "eof" << std::endl;
  }
  std::cout << "Hello, " << cmd<< "!\n";
  std::cin.clear();
  std::cin.ignore();

  while ( getline( std::cin, cmd) ) {
    std::cout << " " << cmd<< std::endl ;
    if (cmd == "exit") {
        break;
    }
  }

  return 0;
}
0 Answers
Related