检查 stdin 输入而不是作为单独的条目

Check stdin input not as individual entries

我给了一个 while 语句两个条件,但它似乎没有像我想要的那样工作。

cout << "Enter S if you booked a single room or D for a double room and press enter." << endl;
cin >> rtype;
while(rtype !='S' && rtype !='D')
{
    cout << "That is not a valid room type, please try again." << endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin >> rtype;
}

如果我输入 "Sfbav",它会将输入视为有效,因为第一个字符是 'S',并忽略那里还有其他字符会使它成为无效输入。

如何更改此设置,以便输入仅需 'S''D' 即可被视为正确?

你可以得到整行,看看有多少个字符。如果它超过 1,那么您就知道用户输入了 Sfbav 或其他内容。

while (true) {
    std::string line; // stores the whole input that the user entered
    std::getline(std::cin, line); // get the whole input
    if (line.size() != 1) // if it does not have exactly 1 character, than it is invalid
        std::cout << "That is not a valid room type, please try again.\n";
    else { // if it has only 1 character, everything is ok
        rtype = line.front();
        break;
    }
}

选项 1

将令牌作为字符串读取并将其与 "S""D" 进行比较。

std::string rtype;
cin >> rtype;
while(rtype != "S" && rtype != "D" )
{
   cout << "That is not a valid room type, please try again." << endl;
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(), '\n');
   cin >> rtype;
}

选项 2

将整行作为字符串读取并将其与 "S""D".

进行比较
std::string rtype;
getline(cin, rtype);
while(rtype != "S" && rtype != "D" )
{
   cout << "That is not a valid room type, please try again." << endl;
   getline(cin, rtype);
}

if your rtype is char

在这种情况下,我更喜欢使用 std::setw( 1 ) 来避免获得多个字符,例如:

char rtype;
std::cin >> std::setw( 1 ) >> rtype;  // Sabc
std::cout << rtype << '\n';           // S

和:

#include <iomanip>