当用户使用 char 变量输入多个字符时出现错误
Bug when user input more than a character with char variable
我正在制作一个简单的程序,如果用户输入 'z' 则显示 "True",如果用户输入其他任何内容则显示 "False"。
但是,问题是当用户输入超过一个字符时,例如当用户输入 'zz' 时,输出是
True
Input : True
并且当用户输入 'zs' 时应该是错误的,输出是
True
Input : Wrong
这是我的代码
#include <iostream>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while(true){
cout << "Input : ";
cin >> input;
if(input=='z'){
cout << "True" << endl;
} else {
cout << "Wrong" << endl;
}
}
return 0;
}
我想知道是否有办法在不将变量类型更改为字符串的情况下防止这种情况发生?
我在 Windows 10 x64
上使用带有 GNU GCC 编译器的 CodeBlocks 16.04 (MinGW)
你不能通过读取单个字符来做到这一点。关键是如果用户输入例如zz 他实际上 did 输入了这两个字符,这些是你在阅读时得到的字符来自 cin
.
只需按照建议阅读 std::string
并仅检查字符串的第一个字符。这和你所做的一样简单。
所以你可能想要这个:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
if (input.length() > 0 && input[0] == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
}
return 0;
}
绝对有可能您只需要检查第一个字符并确保它是唯一输入的字符,而不是刷新缓冲区以删除字符串的其余部分。
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
//Check if the input is z and there is only 1 character inputted
if (cin.rdbuf()->in_avail() == 1 && input == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
//Flush the buffer
cin.clear();
cin.ignore(INT_MAX, '\n');
}
return 0;
}
我正在制作一个简单的程序,如果用户输入 'z' 则显示 "True",如果用户输入其他任何内容则显示 "False"。 但是,问题是当用户输入超过一个字符时,例如当用户输入 'zz' 时,输出是
True
Input : True
并且当用户输入 'zs' 时应该是错误的,输出是
True
Input : Wrong
这是我的代码
#include <iostream>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while(true){
cout << "Input : ";
cin >> input;
if(input=='z'){
cout << "True" << endl;
} else {
cout << "Wrong" << endl;
}
}
return 0;
}
我想知道是否有办法在不将变量类型更改为字符串的情况下防止这种情况发生?
我在 Windows 10 x64
上使用带有 GNU GCC 编译器的 CodeBlocks 16.04 (MinGW)你不能通过读取单个字符来做到这一点。关键是如果用户输入例如zz 他实际上 did 输入了这两个字符,这些是你在阅读时得到的字符来自 cin
.
只需按照建议阅读 std::string
并仅检查字符串的第一个字符。这和你所做的一样简单。
所以你可能想要这个:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
if (input.length() > 0 && input[0] == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
}
return 0;
}
绝对有可能您只需要检查第一个字符并确保它是唯一输入的字符,而不是刷新缓冲区以删除字符串的其余部分。
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
//Check if the input is z and there is only 1 character inputted
if (cin.rdbuf()->in_avail() == 1 && input == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
//Flush the buffer
cin.clear();
cin.ignore(INT_MAX, '\n');
}
return 0;
}