I am doing an assignment for school and I am using an array filled with the ICAO words alphabet. The user enters a letter and then the program displays what ICAO word goes with the letter provided. I am using an index variable to get the ICAO word from the ICAO array. However I need to check that the user only enters a single letter to go into the char input variable. How can I do this? Below is what I have but is not working correctly. It reads the first letter and spits out the result from the first letter, then closes right away.
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; }
I figured it out from a little of each of the answers. The solution is below:
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;