问题描述
#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;
}
编译时出现问题。它将编译只是很好,但没有显示,然后程序将停止运行。所以我的问题是,这段代码有什么问题?
The issue comes in when you compile it. It will compile just fine but nothing displays and then the program will cease to run. So my question is, what is wrong with this code?
推荐答案
您的代码有几个问题:
cout < charStr;
应为:
cout << charStr;
如果使用g ++ -Wall参数(警告全部)进行编译,
If you compile with the g++ -Wall argument (warning all), that error becomes easily apparent.
此外,您从不设置stringLength的值!这是一个例子,为什么你通常不应该使用全局变量 - 可能很难跟踪它们。 stringLength的unset值可能会做奇怪的事情,这取决于你的编译器 - 许多编译器将简单地将值初始化为0,但有些会将其设置为随机值。这个未定义的行为可以导致严重的头痛,所以非常小心,并尝试始终初始化您的变量,在适当的时候(这通常是一个更大的问题指针,但问题仍然可以为其他变量)。
Also, you never set the value of stringLength! This is one example of why you generally should not use global variables--it can be hard to keep track of them. The unset value of stringLength could do weird things depending on your compiler--many compilers will simply initialize the value to 0, but some will set it to a random value. This undefined behavior can cause major headaches, so be very careful about that, and try to always initialize your variables when appropriate (this is generally a bigger issue with pointers, but the problem can still remain for other variables).
一个固定的程序如下:
#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 ++标准库字符串,尽管在这种情况下,你的代码确实不需要字符串。
Still using global variables, but I think this is a bit more of an appropriate use of them. I'm not sure what you were trying to accomplish by having the global char* string, just a headache waiting to happen and not really giving any advantages in your code. Generally in C++ it's better to use the C++ standard library string when you can--though in this case, your code really didn't need strings.
这篇关于随机字符串生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!