为什么在触发"else"时循环本身?这是因为所谓的内存分配吗?

Why does the loop loop itself when "else" is triggered? Is this because of things called memory allocation?

本文关键字:是因为 所谓 内存 分配 else 为什么 循环      更新时间:2023-10-16

我只是一个初学者,正在尝试老师教我们使用的一些代码和教科书中的内容。

该程序旨在让用户输入他们的名字并输入密码作为系统要求他们输入的密码。

有人可以向我解释为什么这个循环在触发时else不断循环吗?

另外,cin.ignore 对字符名称的记忆有什么作用? 为什么80比20好?

而且,为什么随机数实际上不是随机的?每次我运行它时,数字都是一样的。

非常感谢大家!

#include <iostream>
#include <cstdlib>
using namespace std;
int main () 
{
char name[20];
int pwd, rand1, rand2;
for (int i=0;i<1; i++)
{
cout<<"Name:               ";
cin.get(name, 20);
cin.ignore(80, 'n');
cout<<endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand()%6);
cout<<"Password: "<<rand1<<"*"<<rand2<<"=  "; 
cin>>pwd;
if(pwd == rand1*rand2)
{ 
cout<<endl<<"Welcome to our main page, "<<name<<"."<<endl;
}
else 
{
cout<<"Wrong password, type again." <<endl;
i--;
}
}
return 0;
}

首先,代码的格式将帮助您更好地理解。 还要避免使用命名空间 std,这是不好的做法,并且用名称使全局范围混乱。如果您不想每次都写 std::cout、std::cin 等,请使用 std::xxxx。

重新格式化的代码:

#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;
using std::endl;
int main () 
{
char name[20];
int pwd, rand1, rand2;
for (int i = 0; i < 1; i++) {
cout << "Name:               ";
cin.get(name, 20);
cin.ignore();
cout << endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand() % 6);
cout << "Password: " << rand1 << "*" << rand2 << "=  "; 
cin >> pwd;
cin.ignore();
if(pwd == rand1*rand2) { 
cout << endl << "Welcome to our main page, " << name << "." << endl;
} else {
cout << "Wrong password, type again." << endl;
i--;
}
}
return 0;
}

其次,正如您在上面的代码中看到的那样,在 cin>> pwd 之后添加了行 cin.ignore(); 在您的代码获取 cin>>名称之前,在输入中留下"",忽略"",获取 cin>> pwd,在输入中保留"",循环并将输入读取为空并带有"",在输入中留下另一个"",第一个""由 ci.ignore() 删除,第二个""由 cin>> pwd 读取,...等。或者至少我是这样理解的。

有人回答了第一个问题:因为当你 i 时--,for 循环中的 i 会不断减少然后增加。 然后,
如果您的输入长度超过 20,程序可能会停止。所以你需要cin.ignore(80, '')来忽略多余的输入。数字80只是一个很大的数字。您可以将其替换为另一个数字 - 仅当它足够大时。
你应该随着时间的推移使用srand。srand(time(null))可能会有所帮助。