为什么在触发"else"时循环本身?这是因为所谓的内存分配吗?
Why does the loop loop itself when "else" is triggered? Is this because of things called memory allocation?
我只是一个初学者,正在尝试老师教我们使用的一些代码和教科书中的内容。
该程序旨在让用户输入他们的名字并输入密码作为系统要求他们输入的密码。
有人可以向我解释为什么这个循环在触发时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))
可能会有所帮助。
相关文章:
- 如何在C++中围绕任意值实现我所谓的"wraparound sort"?
- C++ : "undefined reference to"可能是因为CMake文件
- 下面的代码无法编译。也许是因为 std=c++2a 的 GCC 仍然没有完全跟上最新的草案
- 与2017年相比,我认为这是因为它没有识别我的课程
- 在iostream或C++其他地方有没有所谓的时间
- C 链接器警告是因为虚拟击D驱动器 / clang
- OpenGL显示空白屏幕.可能是因为着色器
- 为什么在触发"else"时循环本身?这是因为所谓的内存分配吗?
- 树类的节点出错,可能是因为专用节点成员
- 分段错误.是因为指针不好吗?
- 是因为两个查找而不是一个查找,所以速度变慢了吗
- Boost multiprecision失败是因为complex的实现试图在_Isinf或_Isnan等内部函数中强制转
- 无法使用 printui 安装驱动程序。这是因为驾驶证书过期了吗?
- 使用QWebview给出编译错误,但不是因为Qt += webkit从.pro文件中缺失
- 如何跟踪使用过的DLL(是不是所谓的DLL地狱?)
- 名称空间函数定义中的这种所谓查找是什么