#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
char *charStr;
int stringLength;
void genRandom() {
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < stringLength; ++i) {
charStr[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
charStr[stringLength] = 0;
}
int main()
{
while(true)
{
genRandom();
cout < charStr;
}
return 0;
}
问题是在你编译的时候出现的。它会编译得很好,但没有任何显示,然后程序将停止运行。所以我的问题是,这段代码有什么问题?
最佳答案
您的代码有几个问题:
cout < charStr;
应该是:
cout << charStr;
如果您使用 g++ -Wall 参数(警告所有)进行编译,该错误将变得很明显。
此外,您永远不会设置 stringLength 的值!这是为什么您通常不应使用全局变量的一个示例——可能很难跟踪它们。 stringLength 的未设置值可能会做一些奇怪的事情,具体取决于您的编译器——许多编译器会将值简单地初始化为 0,但有些会将其设置为随机值。这种未定义的行为可能会导致严重的问题,因此对此要非常小心,并尝试始终在适当的时候初始化变量(这通常是指针的一个更大的问题,但对于其他变量来说问题仍然存在)。
固定程序如下:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
while(true)
{
cout << genRandom();
}
return 0;
}
仍然使用全局变量,但我认为这更适合使用它们。我不确定您试图通过拥有全局 char* 字符串来完成什么,只是等待发生的头痛,并没有真正在您的代码中提供任何优势。通常在 C++ 中,最好尽可能使用 C++ 标准库字符串——尽管在这种情况下,您的代码确实不需要字符串。
关于c++ - 随机字符串生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5053411/