c++ 2D Array输入验证

  • 本文关键字:验证 Array 2D c++ c++
  • 更新时间 :
  • 英文 :


评委给A组选手打0到10分。我希望我的程序只接受0-10的值只接受用户输入,这是我的代码

string name [5];
for(int i=0;i<5;i++)
{
cout << "Enter participant's name: n";
cin >> name[i];
cout<<"Enter scores for " << name[i] <<endl;
for(j=0;j<2;j++)

{
cin>>scores[i][j];
if (scores[i][j] < 0 && scores[i][j] > 10)
cout << "Invalid number. Try again.";
}
}

for(int i=0; i<5; i++)
{
sum = 0;
for(j=0; j<2; j++)
{
sum += scores[i][j];
}
cout<<"Total scores of " << name[i] << " " <<" is "<<sum<<endl;
}
return 0;
}

在这里,您实际上声明输入应该同时小于0且大于10。基本上这个条件永远不会得到满足。所以修改这个:

if (scores[i][j] < 0 && scores[i][j] > 10)

:

if (scores[i][j] < 0 || scores[i][j] > 10)

但是无论如何,您仍然将数据输入到数组中。因此,让我们首先将其输入到一个变量中,如果满足条件,则将其输入到数组中。

j = 0;
while (j < 2)
{
int score = 0;
cin >> score;
if (score < 0 || score > 10)
{
cout << "Invalid number. Try again.";
continue;    // This says to skip to the next iteration.
}
// If the score is within the boundaries, assign it to the array.
scores[i][j] = score;
j++;
}

最新更新