我在编写老师的练习时遇到了这个问题。我尝试输入"IDcheck"作为字符或字符串,但行:"您输入了错误的ID,请重试:"无限循环,所以我希望它停止并从头开始。我现在该怎么办?请帮助我,谢谢。
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
const int ID = 123;
const int password = 123456;
int IDcheck, passwordcheck;
cout << "Enter the ID: "; cin >> IDcheck; cout << endl;
do
{
cout << "You entered the wrong ID, please try again: ";
cin >> IDcheck;
cout << endl;
} while (ID != IDcheck);
cout << "Enter the password: "; cin >> passwordcheck; cout << endl;
do
{
cout << "You entered the wrong password, please try again: ";
cin >> passwordcheck;
cout << endl;
} while (password != passwordcheck);
cout << "Welcome to my world!" << endl;
system("pause");
return 0;
}
do { ... } while (...)
将始终运行,测试在循环结束时执行。可能会运行while (...) { ... }
,测试在每轮开始之前执行。
如果您希望它循环当且仅当您犯错时,请考虑使用直线while
循环。
您正在使用 do { statement(s(; }while( condition ( 但在你的代码中不需要 do while 循环。In do { statement(s(; }while( condition ( 请注意,条件表达式出现在循环的末尾,因此循环中的语句在测试条件之前执行一次。
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
const int ID = 123;
const int password = 123456;
int IDcheck, passwordcheck;
cout << "Enter the ID: "; cin >> IDcheck; cout << endl;
while (ID != IDcheck);
{
if(ID != IDcheck)
{
cout << "You entered the wrong ID, please try again: ";
}
else {
cout << "Enter the ID: "; cin >> IDcheck; cout << endl;
cout << endl;
}
}
cout << "Enter the password: "; cin >> passwordcheck; cout << endl;
while (password != passwordcheck);
{
if((password != passwordcheck)
{
cout << "You entered the wrong password, please try again: ";
}
else {
cout << "Enter the password: "; cin >> passwordcheck; cout << endl;
cout << endl;
}
}
cout << "Welcome to my world!" << endl;
system("pause");
return 0;
}
使用while(..){..}
循环,因为无论条件如何,do{...}while(...)
循环都会至少运行一次,此外,循环只会在您输入 id123
时终止,因此如果您尝试输入一个不是"123"
的字符串,循环将无限期地进行。此外,IDCheck
的类型定义为int
因此,如果输入包含字母的字符串,则IDcheck
的值将更改为字符串的第一个整数部分。 例如,如果输入 12ab,则IDCheck
的值将设置为 12。