我正在为学校做作业,我正在使用一个填充了 ICAO 单词字母表的数组。用户输入一个字母,然后程序会显示与提供的字母对应的 ICAO 词。我正在使用索引变量从 ICAO 数组中获取 ICAO 词。但是我需要检查用户是否只输入一个字母进入 char 输入变量。我怎样才能做到这一点?以下是我所拥有的但无法正常工作。它读取第一个字母并从第一个字母中吐出结果,然后立即关闭。
int main()
string icao[26] =
"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
"Golf",
"Hotel",
"India",
"Juliet",
"Kilo",
"Lima",
"Mike",
"November",
"Oscar",
"Papa",
"Quebec",
"Romeo",
"Sierra",
"Tango",
"Uniform",
"Victor",
"Whiskey",
"X-ray",
"Yankee",
"Zulu"
};
int index;
char i;
cout << "Enter a letter from A-Z to get the ICAO word for that letter: ";
while(!(cin >> i))
{
cout << "Please enter a single letter from A-Z: ";
cin.clear();
cin.ignore(1000,'\n');
}
i = toupper(i);
index = int(i)-65;
cout << "The ICAO word for " << i << " is " << icao[index] << ".\n";
cin.get();
cin.get();
return 0;
我从每个答案中了解了一点点。解决方案如下:
int main()
//store all the ICAO words in an array
string icao[26] =
{"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
"Golf",
"Hotel",
"India",
"Juliet",
"Kilo",
"Lima",
"Mike",
"November",
"Oscar",
"Papa",
"Quebec",
"Romeo",
"Sierra",
"Tango",
"Uniform",
"Victor",
"Whiskey",
"X-ray",
"Yankee",
"Zulu"
};
int index;
string input = "";
cout << "Enter a letter from A-Z to get the ICAO word for that letter: ";
// get the input from the user
cin >> input;
//get the first character the user entered in case the user entered more than one character
char input1 = input.at(0);
//if the first character is not a letter, tell the user to enter a letter
while (!isalpha(input1))
{
cout << "Please enter a letter from A-Z: ";
cin >> input;
input1 = input.at(0);
cin.clear();
}
//capitalize the input to match the internal integer for the characters
input1 = toupper(input1);
index = int(input1)-65;
cout << "The ICAO word for " << input1 << " is " << icao[index] << ".\n";
cin.get();
cin.get();
return 0;
最佳答案
你的支票
while( !cin )
检查流是否失败。文件结束或其他原因。你想要完成的是更棘手的。也许你可以做一个 getline( cin, string ) 来检查用户是否只输入了一个字符然后回车。
string input;
getline( cin, input );
if ( input.size() == 1 && *input.c_str()>='A' && *input.c_str()<='Z' )
或者类似的东西。请注意,条件与我认为您的 while 语句的意图相反。
关于C++ 检查 cin 的有效数据不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5697243/