C++ 如果条件不满足,如何无限期地重做操作?
下面是我的代码:C++ 如果条件不满足,如何无限期地重做操作?,c++,arrays,input,element,C++,Arrays,Input,Element,下面是我的代码: #include <conio.h> #include <iostream> #include <string> #include <iomanip> using namespace std; int n; int a[10]; int main() { cout<<"Insert amount of data\n"; cin>>n; for (int
#include <conio.h>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int n;
int a[10];
int main()
{
cout<<"Insert amount of data\n";
cin>>n;
for (int i=0; i < n; i++){
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
if (a[i]<1 || a[i]>3){
cout<<"Please insert only the number 1-3\n";
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
}
}
for (int i=0; i<n;i++) {
cout<<a[i];
}
}
这是正确的。但是,如果我再次输入
5
,它将被输入到数组中。我只希望数组的数字是1-3。那么,在键入数字1-3之前,如何使if语句循环?您已经掌握了使用条件的循环的,因此让我们添加一个循环
而不是:
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
couta[i];
你可以做:
do {
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
} while(a[i] < 1 || a[i] > 3);
do{
couta[i];
}而(a[i]<1 | | a[i]>3);
您还可以添加错误检查。如果用户关闭输入流,您的程序将永远旋转
do {
cout<<"Insert number (1, 2, or 3)= ";
if(not (cin>>a[i])) return 1; // failed to read an int, abort the program
} while(a[i] < 1 || a[i] > 3);
do{
couta[i]))返回1;//读取int失败,中止程序
}而(a[i]<1 | | a[i]>3);
要循环直到获得有效值,可以使用循环构造:for
,或while
或do…while
。或者您可以使用goto
。
do {
cout<<"Insert number (1, 2, or 3)= ";
if(not (cin>>a[i])) return 1; // failed to read an int, abort the program
} while(a[i] < 1 || a[i] > 3);