[英]Function checking valid input, loop repeating continuosly
我有这段代码,我无法摆脱“ elegir()”函数中的“ while”循环。 输入错误时,它将永远循环。 我知道我可以用其他条件来完成它,但是我想知道是否有可能使它与“ while”一起运行。 谢谢。
Code here:
#include "stdafx.h"
#include <iostream>
int const strsize = 100;
struct bop {
char fullname[strsize]; // real name
char title[strsize]; // job title
char bopname[strsize]; // secret BOP name
int preference; //89 0 = fullname, 1 = title, 2 = bopname
};
char elegir();
using namespace std;
int main(){
bop miembros[3] = {
{
"Luciano",
"Doctor",
"Zahyr",
1
},
{
"Sabrina",
"Licenciada",
"Mumu",
2
},
{
"Andres",
"Verdulero",
"Uruguayo",
0
}
};
cout
<< "Elija como desea que se muestren los miembros de la 'Orden':" << endl
<< "a) Por nombre b) Por titulo\n"
"c) Por nombre secreto d) Por la eleccion del miembro\n";
char eleccion;
eleccion = elegir();
while (eleccion == 'a' || eleccion == 'b' || eleccion == 'c' || eleccion == 'd'){
switch (eleccion){
case 'a' : cout << "Mostrando miembros por 'Nombre':\n";
for (int x=0;x<3;x++){
cout << miembros[x].fullname << endl;
}; break;
case 'b' : cout << "Mostrando miembros por 'Titulo':\n";
for (int x=0;x<3;x++){
cout << miembros[x].title << endl;
}; break;
case 'c' : cout << "Mostrando miembros por 'Nombre secreto':\n";
for (int x=0;x<3;x++){
cout << miembros[x].bopname << endl;
}; break;
case 'd' : cout << "Mostrando miembros por preferencia del miembro: \n";
for (int x=0;x<3;x++){
if ( miembros[x].preference == 0 )
cout << miembros[x].fullname << endl;
else if ( miembros[x].preference == 1 )
cout << miembros[x].title << endl;
else
cout << miembros[x].bopname << endl;
}; break;
}
cin
>> eleccion;
}
return 0;
}
char elegir(){
char e;
cin
>> e;
cin.clear('\n');
while (e != 'a' || e != 'b' || e != 'c' || e != 'd'){
cout << "Eleccion incorrecta, elija nuevamente\n";
cin
>> e;
cin.clear('\n');
}
return e;
}
你的问题在这一行
while (e != 'a' || e != 'b' || e != 'c' || e != 'd'){
如果e
为“ a”会怎样?
e != 'a' is false
e != 'b' is true
e != 'c' is true
e != 'd' is true
因此您的while测试评估为
(false || true || true || true)
因为您正在使用||
这评估为
true
解决方案-请勿使用||
(或)在这里,使用&&
(和)
除了“黑暗”答案的建议外,在要求输入之前,您还需要cin.clear()
。
//main()
cin.clear(); <-- include this line
cin >> eleccion;
//Similarly in elegir()
char elegir(){
char e;
cin >> e;
cin.clear('\n');
while (e != 'a' && e != 'b' && e != 'c' && e != 'd'){
cout << "Eleccion incorrecta, elija nuevamente\n";
cin.clear(); <-- include this line
cin >> e;
cin.clear('\n');
}
return e;
}
包含cin.clear()
清除错误标志,以防止无限循环。 这是一个教程,它可能包括示例,可以帮助您详细了解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.