【发布时间】:2017-04-25 07:13:04
【问题描述】:
所以我正在尝试学习 C++ 中的循环和条件,所以我决定编写一个程序,为用户生成一个随机密码。出于某种原因,代码可能工作了 1/5 次,但其余时间它只是给了我“以非零状态退出”。 谢谢, 埃文
#include <iostream>
#include <cstdlib>
#include <chrono>
#include <thread>
#include <time.h>
using namespace std;
int main()
{
using namespace std::this_thread;
using namespace std::chrono;
// Vars
string lett;
int input;
string password("");
string lettArray [] = {"a", "b", "c", "d", "e","f", "g", "h", "i", "j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// Prompt
cout << "How long would you like your password to be?";
cin >> input;
// Loop
for(int i = 0; i < input; i++)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
srand((time_t)ts.tv_nsec);
int random = (rand() % 26 + 1);
lett = lettArray[random];
password = password + lett;
sleep_for(milliseconds(10));
cout << "." << endl;
if (random == 0 )
break;
}
// Output
cout << password << endl;
return 0;
}
【问题讨论】:
-
不确定是问题所在,但将分配中的 +1 删除为随机。您需要 0 到 25 范围内的数字,而不是 1 到 26。
-
@MathieuVanNevel 我猜这是增加熵的尝试(在这里不太可能获得很多...)
-
其实有几种情况你会重新调用
srand。这不是其中之一 -
链接页面上的示例代码调用了srand两次,所以不可以多次调用。
-
一些弊端:没有测试函数调用是否失败。例如,
clock_gettime可能已经失败,导致无效的ts@WayneTanner 已经锁定了一个很容易引发崩溃的大但未定义的行为:没有lettArray[26]。建议在 GDB 下运行程序以查看崩溃的确切位置,然后检查崩溃现场周围的变量。
标签: c++ arrays loops compiler-errors conditional