C++ 字符变量作为Y/N问题的输入
我在问用户是否需要饮料。用户只能键入C++ 字符变量作为Y/N问题的输入,c++,codeblocks,C++,Codeblocks,我在问用户是否需要饮料。用户只能键入Y表示是,键入N表示否,然后出现最后一个对话框。我做了一个char:char答案然后添加了一个if语句。如果用户键入Y或N,则一切正常。但是,只要用户键入Y(+任意字母),例如YHTY,程序仍会接受它(对于N)。我只需要一个字母的答案Y或N,除此之外的其他答案将导致else对话 代码如下: #include <iostream> using namespace std; int main() {
Y
表示是,键入N
表示否,然后出现最后一个对话框。我做了一个char
:char答案
然后添加了一个if
语句。如果用户键入Y
或N
,则一切正常。但是,只要用户键入Y(+任意字母)
,例如YHTY
,程序仍会接受它(对于N
)。我只需要一个字母的答案Y
或N
,除此之外的其他答案将导致else
对话
代码如下:
#include <iostream>
using namespace std;
int main()
{
char answer;
cout << "Do you want a drink? " << endl;
cout << "Y/N: ";
cin >> answer;
if(answer == 'Y' || answer == 'y'){
cout << "Okay. I'll bring you some." << endl;
} else if(answer == 'N' || answer == 'n'){
cout << "Okay suit yourself." << endl;
} else{
cout << "Please type just Y/N." << endl;
}
return 0;
}
#包括
使用名称空间std;
int main()
{
答案;
cout由于要处理多个字符,必须将变量设置为字符串
#include <string>
string answer;
cout << "Do you want a drink? " << endl;
cout << "Y/N: ";
getline(cin, answer);
if (answer == "Y" || answer == "y") {
#包括
字符串回答;
coutcin
将只接受输入的第一个字母作为答案
,因为它的数据类型是字符
,我看这里没有任何问题,它应该满足您的需要。
您可以通过以下代码检查上述声明:
#include <iostream>
using namespace std;
int main()
{
char answer,a2;
cout << "Do you want a drink? " << endl;
cout << "Y/N: ";
cin >> answer;
cin>>a2;
cout<<endl<<a2<<endl;
if(answer == 'Y' || answer == 'y'){
cout << "Okay. I'll bring you some." << endl;
} else if(answer == 'N' || answer == 'n'){
cout << "Okay suit yourself." << endl;
} else{
cout << "Please type just Y/N." << endl;
}
return 0;
}
当我试着运行代码时,它工作得非常好。你能解释一下char和char[]之间的区别吗?第二个帮助了我。谢谢!char[]
表示一个char
数组,我们可以称之为string
。在C/C++中,在char
的array
中,总是有一个空字符\0
表示string
的结尾,即如果有char[5]
且值为“YES”然后内部数组将是'Y','E','S','\0',
,更多信息:@Jerico,如果您发现答案有效,请接受此答案。谢谢
#include <iostream>
using namespace std;
int main()
{
char str[3], answer;
cout << "Do you want a drink? " << endl;
cout << "Y/N: ";
cin >> str;
answer=str[0];
if(str[1]!='\0'){ // Checks if second char is not NULL char i.e. str length is not 1
cout << "Please enter one character only." << endl;
} else if(answer == 'Y' || answer == 'y'){
cout << "Okay. I'll bring you some." << endl;
} else if(answer == 'N' || answer == 'n'){
cout << "Okay suit yourself." << endl;
} else{
cout << "Please type just Y/N." << endl;
}
return 0;
}