我遇到输入错误的问题。我的输入已经过验证,但我的错误消息“无效范围。请输入范围0-100:”如果输入无效则不显示。
以下是一个例子:
Please Enter Grade 1: 101 (It does not accept input)
Please Enter Grade 1: 321 (It does not accept input)
而不是显示:
Please Enter Grade 1: 101 (It does not accept input)
Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 1:
这是我的代码:
for(vector<double>::size_type i = 0; i < 15; i++)
{
do
{
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
}
while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
{
cout << "Invalid Rage. Please Enter Range 0-100:\n";
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
}
}
答案 0 :(得分:1)
您的while()
条件应为
while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0)
并使用此代码
for(vector<double>::size_type i = 0; i < 15; i++)
{
int c=0;
do
{
if(c!=0) //checking that we didnt entered loop for first time
cout << "Invalid Rage. Please Enter Range 0-100:\n";
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
c++;
}
while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
}
答案 1 :(得分:1)
您正在将do
构造与while
混合。使用两者都不是。您在while
中的测试也没有意义。它可以同时减少和。编辑以下内容,它应该可以正常工作
for(vector<double>::size_type i = 0; i < 15; i++)
{
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0); // or not and
{
cout << "Invalid Rage. Please Enter Range 0-100:\n";
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
}
}
答案 2 :(得分:1)
你的状况不对。
std::vector<double> gradesVector;
gradesVector.reserve(15);
for (std::vector<double>::size_type i = 0; i < 15; i++)
{
double grade;
std::cout << "Please Enter Grade " << i + 1 << ": " << std::flush;
std::cin >> grade;
while (grade < 0.0 || grade > 100.0)
{
std::cout << "Invalid Range. Please Enter Range 0-100:\n";
std::cin >> grade;
}
gradesVector.push_back(grade);
}
此外,我只会在矢量有效后将等级添加到矢量中。