我正在学习C++,我不完全理解case是如何在开关语句中工作的。我有以下代码:
bool accept3() {
int tries = 1;
while (tries<4) {
std::cout<<"Do you want to proceed (y or n)?\n";
char answer = 0;
std::cin>>answer;
switch(answer) {
case 'y':
return true;
case 'n':
return false;
default:
std::cout<<"Sorry, but I don't understand that.\n";
tries ++;
}
}
std::cout << "I'll take that as a no.\n";
return false;
}
int main()
{
//accept();
//accept2();
accept3();
}当您输入、'y‘、'n’或任何其他不符合这两个定义的情况的单个字符时,它的工作原理是预期的。
当您输入以n开头的任何字符串时,它仍然将其作为'n‘大小写。为什么要这么做?我如何使这更准确,使它只接受'n‘而不是'no','no way’或任何以‘n’开头的其他字符串。
谢谢!
发布于 2022-02-21 22:31:16
当您输入以n开头的任何字符串时,它仍然将其作为'n‘大小写。为什么要这么做?
因为您要求cin读取单个char,所以它就是这样做的。operator>>(char&)忽略前导空格(如果有的话),然后读取1 char。任何后续字符(如果有的话)都留在输入缓冲区中,以供以后读取。
如何使这个更精确,使它只接受'n‘而不是'no','no way’或任何以'n‘开头的字符串。
使用cin.getline()或std::getline()代替,然后比较整行,例如:
bool accept3() {
int tries = 1;
std::string answer;
do {
std::cout << "Do you want to proceed (y or n)?\n";
std::getline(std::cin >> std::ws, answer);
if (answer == "y")
return true;
if (answer == "n")
return false;
std::cout << "Sorry, but I don't understand that.\n";
++tries;
}
while (tries < 4);
std::cout << "I'll take that as a no.\n";
return false;
}发布于 2022-02-21 22:05:38
这是一个棘手的问题,因为如果将带有空格的文本输入到终端中,比如"d“,那么将连续4次看到循环触发器,因为"cin >>应答”将行拆分为单独的输入(这称为标记化)。
下面的代码演示如何将整行输入正确地解析为一个菜单命令:
#include <iostream>
#include <string>
bool accept3() {
int tries = 1;
while (tries < 4) {
std::cout << "Do you want to proceed (y or n)?\n";
std::string answerStr;
std::getline(std::cin, answerStr);
char answer = '\0';
if (answerStr.size() == 1) {
answer = answerStr[0];
}
switch (answer) {
case 'y':
return true;
case 'n':
return false;
default:
std::cout << "Sorry, but I don't understand that.\n";
tries++;
}
}
std::cout << "I'll take that as a no.\n";
return false;
}
int main()
{
//accept();
//accept2();
accept3();
}https://stackoverflow.com/questions/71213495
复制相似问题