[英]How to detect a single Enter key in C++?
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).如果您只是按 Enter,国家名称应设置为默认国家名称 (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.我对如何将输入检测为单个 Enter 键或普通字符串感到困惑。
Use std::getline()
to read a whole line of user input up to the ENTER key (which will be read and discarded for you).使用std::getline()
读取一整行用户输入直到ENTER键(将为您读取和丢弃)。 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";
Try this尝试这个
std::cout << "Country name: ";
std::getline(std::cin, countryName);
if(countryName==""){
countryName="USA"
}
also use cin.ignore();也使用cin.ignore(); after every use of cin>> if you have to use getline() in the next line.每次使用 cin>> 后,如果您必须在下一行使用 getline()。
you can also use cin.sync();你也可以使用 cin.sync(); cin.get(); cin.get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.