我正在为学校做一项作业,我正在使用一个包含国际民航组织字母表的数组。用户输入一个字母,然后该程序显示出国际民航组织的单词与所提供的信件的内容。我使用一个索引变量从民航组织数组中获取民航组织的单词。但是,我需要检查用户只输入一个字母才能进入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;发布于 2011-04-17 23:58:14
你的支票
while( !cin ) 检查流是否失败。或者其他原因。你想要完成的事情更棘手。也许您可以做一个getline( cin,string )来检查用户是否只输入一个字符,然后点击返回。
string input;
getline( cin, input );
if ( input.size() == 1 && *input.c_str()>='A' && *input.c_str()<='Z' )或者其他类似的东西。请注意,这个条件与我认为您的with语句的意图正好相反。
发布于 2011-04-17 23:55:23
好的。
所以std:cin是缓冲的,所以你可能需要输入"a“才能让它正常工作。
这对我来说很管用:
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“,它可以工作,但当我试图访问数组时会出现分段错误。
https://stackoverflow.com/questions/5697243
复制相似问题