我正在做学校作业,正在使用填充有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陈述的意图相反。

10-06 03:04