noob程序员在这里。如果我提供的信息不够充分,请上大学的第一门CS课并在此处发布第一篇帖子。
仍然试图找出循环。似乎可以得到它,但是一旦循环中存在循环或循环中是否存在语句,我就会被抛弃,也不知道如何进行。对于我的任务,我需要进行以下操作。
您要处理文件中的所有记录吗? (y / n)宽 请输入y或n。 您要处理文件中的所有记录吗? (y / n)n 输入要处理的记录数:两个 XXXXXXXXXX错误-非数字或负值,请重试 输入要处理的记录数:10
这是我的代码:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
do{
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
}
else{
notDone = false;
}
}
}else if(a != 'y' or a != 'n');
cout <<"Please enter either y or n." << endl;
}while( a != 'y');
答案 0 :(得分:0)
大多数问题都在注释中说明,这是我的解决方法:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
while (a != 'y') {
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
} else {
notDone = false;
}
}
} else if(a != 'y' or a != 'n') {
cout <<"Please enter either y or n." << endl;
cin >> a; // Need to get new input because old one is invalid.
}
};
我也看不到如何使用notDone
。另外,我强烈建议您使用适当的缩进,在关键字周围使用空格,例如while
,for
,if
,else
,因为这是一种很好的样式。
答案 1 :(得分:0)
您只需将y / n请求从循环中移出,那么'a'就永远不会改变其值。看一下您可能想要的更改:
do {
cout << "Would you like to process all the records in the file? (y/n/f) "; //f to break the loop
cin >> a;
bool notDone = true;
if (a == 'n') {
//. . .
} else if (a == 'y') {
//You may want to do something when yes
} else if (a != 'f')
cout <<"Please enter either y/n or f." << endl;
} while( a != 'f')