私は学校の課題を行っており、ICAO 単語のアルファベットで満たされた配列を使用しています。ユーザーが文字を入力すると、プログラムは提供された文字にどの ICAO 単語が合うかを表示します。インデックス変数を使用して、ICAO 配列から ICAO ワードを取得しています。ただし、ユーザーが char 入力変数に入る文字を 1 つだけ入力することを確認する必要があります。これどうやってするの?以下は私が持っているものですが、正しく動作していません。最初の文字を読み取り、最初の文字の結果を吐き出し、すぐに閉じます。
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;