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

时间:2017-04-17 16:43:49

标签: c++ while-loop cin

我给了一个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'视为正确?

3 个答案:

答案 0 :(得分:4)

选项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);
}

答案 1 :(得分:1)

您可以获取整行,并检查它有多少个字符。如果它超过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;
    }
}

答案 2 :(得分:0)

  

如果您的rtypechar

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

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

#include <iomanip>