1

私は学校の課題を行っており、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;
4

2 に答える 2

2

小切手

while( !cin ) 

ストリームが失敗したかどうかを確認します。ファイルの終わりまたはその他の原因。あなたが達成したいことはよりトリッキーです。getline( cin, string ) を実行して、ユーザーが 1 文字だけ入力してから return キーを押したかどうかを確認できます。

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 に答える