我试图创建一个生成随机字母和数字的单词列表生成器,但是我有一个错误,它只能获取列表中的第一个单词,其余只显示2个字母/数字,编译器没有错误,此时感觉就像我没有任何运气就尝试了一切。这是代码:
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <windows.h>
#include <ctime>
using namespace std;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // chars we need for generation
int stringLength = sizeof(alphanum) - 1;
char genRandom(){
return alphanum[rand() % stringLength];
}
int main(){
// WORD LISTS LENGTH
int WordListTotalLength;
int WordListThisLength = 0;
cout << " How many words should be added?" << endl;
cin >> WordListTotalLength;
// WORD LISTS LENGTH ENDS HERE
SetConsoleTitle("LetterNumberGenerator");
srand(time(0));
std::string Str;
int length = 0;
cout << "Enter the length of each word:" << endl;
cin >> length;
length = length - 1;
for(unsigned int i = 0; i < length; ++i){
Str += genRandom();
}
ofstream myfile;
myfile.open("OutputWordlist.txt");
while (WordListThisLength < WordListTotalLength) {
myfile <<Str + genRandom();
myfile << "\n" ;
genRandom();
Str = genRandom();
WordListThisLength = WordListThisLength +1;
}
myfile.close();
cout << "Generation is finished." << endl;
cout << endl;
system("PAUSE");
return 0;
}
但我从&#34; OutputWordlist.txt&#34;如下:
如果输入我想要总共5个单词,每行有10个字母或数字,我最终会这样:
N5VKP15QAW
EN
YK
48
OK
抱歉,如果我的帖子有点模糊,这是我第一次发帖。任何帮助或建议将非常感谢!
答案 0 :(得分:1)
我看了一下你的代码并重构了一下。以下是https://repl.it/JS45/0
的repl.it我对你的代码实际看错了什么感到困惑,但我确实使用了你想要的风格。
我将GenRandom函数更改为GenRandomWord(长度),而不是使用while循环,我使用了for循环,这更容易看出它将运行多长时间
此外,我只打印出字符而不是将其保存到文件中。我相信你可以弄清楚如何做到这一点