1

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

2 回答 2

2

您的支票

while( !cin ) 

检查流是否失败。文件结束或其他原因。你想要完成的事情更棘手。也许你可以做一个 getline(cin, string) 来检查用户是否只输入了一个字符然后按回车键。

string input;
getline( cin, input );
if ( input.size() == 1 && *input.c_str()>='A' && *input.c_str()<='Z' )

或者类似的东西。请注意,条件与我认为您的 while 语句的意图相反。

于 2011-04-17T23:58:14.510 回答
1

好的。

所以 std::cin 被缓冲了,所以你可能需要输入:“a<enter>”才能让它工作。
这对我有用:

cin >> i:  reads the 'a' character.  
cin.get(): reads the enter character.
cin.get(): Waits for me to hit enter a second time before quitting.

注意:如果我键入“1<enter>”,它可以工作,但在尝试访问数组时出现分段错误。

于 2011-04-17T23:55:23.527 回答