我正在为学校做作业,我正在使用一个充满 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;