-3

I am trying to get an input such as 'Country name'. If you just press Enter, Country name should be set to default country name (ex)USA). Otherwise, input string would be set to country name. I am confused to how to detect input as a single Enter key or normal string.

  • Does this answer your question? [Detecting ENTER key in C++](https://stackoverflow.com/questions/42818899/detecting-enter-key-in-c) – kesarling Aug 27 '20 at 02:54

2 Answers2

2

Use std::getline() to read a whole line of user input up to the ENTER key (which will be read and discarded for you). If the returned string is empty, replace it with a default value as needed.

std::cout << "Country name: ";

std::countryName;
std::getline(std::cin, countryName);

if (countryName.empty())
    countryName = "USA";
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • I have another input before these lines. When I am trying to use this code, 'getline' reads input (cin) from another line. – pepicon Aug 27 '20 at 03:55
  • @pepicon then you are not reading the earlier input correctly. Please edit your question to show the actual code you are having trouble with. – Remy Lebeau Aug 27 '20 at 05:41
0

Try this

std::cout << "Country name: ";
std::getline(std::cin, countryName);
if(countryName==""){
    countryName="USA"
}

also use cin.ignore(); after every use of cin>> if you have to use getline() in the next line.

you can also use cin.sync(); cin.get();

himynameisjm
  • 59
  • 1
  • 9
  • "*use `cin.ignore();` after every use of `cin>>` if you have to use `getline()` in the next line*" - and the reason why is explained here: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/) – Remy Lebeau Aug 27 '20 at 05:44