C ++检查cin是否有效数据不起作用

时间:2011-04-17 23:42:36

标签: c++ char cin

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

2 个答案:

答案 0 :(得分:2)

您的支票

while( !cin ) 

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

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

或者那种效果。请注意,该条件与我认为您对while语句的意图相反。

答案 1 :(得分:1)

行。

所以std :: cin是缓冲的,所以你可能需要输入:“a&lt; enter&gt;”使它工作。
这对我有用:

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&lt; enter&gt;”它有效,但在尝试访问数组时出现了分段错误。