进入' q'在第一个for循环期间(这应该会导致它断开.for循环仍打印出来"请输入最多一千个值或输入'Q'退出:"。作为我我没有得到任何类型的编译器错误,我似乎无法弄清楚问题是什么。
unsigned int const size = 10;
StaticArray<int,size> arr;
int input;
for (int i = 0; i < size - 1; i++)
{
cout << "Please enter up to one thousand values or enter 'Q' to exit: " << endl;
cin >> input;
cin.ignore(1000, 10);
if (input == 'Q' || input == 'q')
break;
else
arr.Push(input);
}
//output array
for (int i = 0; i < arr.getSize(); i++)
{
cout << i << ". " << arr.Top() << endl;
arr.Pop();
}
答案 0 :(得分:0)
处理用户输入时,您必须更加小心处理输入,这可能包含预期值和意外值。这是让你入门的东西。
cin >> input;
// Check whether the number was successfully read.
if ( input.fail() )
{
// The read could have failed due to reaching EOF
// or by bad data. Check.
if ( input.eof() )
{
// Do something sensible
}
else
{
// Clear the flags.
input.clear();
// Check whether the user entered Q or q
char quit;
input >> quit;
if ( quit == `Q` || quit == `q` )
{
// Do the needful to quit.
}
else
{
// How do you want to handle the input if user entered
// something else...
}
}
}
else
{
// The number was successfully read
// Do the needful.
// ...
}