【问题标题】:C++ Making a random number/letter generator, something wrong in the codeC++ 制作随机数/字母生成器,代码有问题
【发布时间】:2017-07-07 18:56:42
【问题描述】:

我正在尝试制作一个生成随机字母和数字的单词列表生成器,但是我遇到了一个错误,它只能正确获取列表中的第一个单词,其余的只显示 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;
}

但我从“OutputWordlist.txt”得到的只是以下内容:

如果输入我总共需要 5 个单词,每行有 10 个字母或数字,我会得到这样的结果:

N5VKP15QAW
EN
YK
48
OK

抱歉,如果我的帖子有点模糊,这是我第一次发帖。任何帮助或建议将不胜感激!

【问题讨论】:

  • 使用调试器逐步完成您的代码。
  • 我敢打赌,我对编程非常陌生,所以它的 prolly 看起来也很垃圾!我会查看 Jesper 的链接,谢谢。
  • 请至少通过正确和一致的缩进使您的代码看起来像。您和其他人将阅读您的代码的次数比编写代码的次数要多得多。 format.krzaq.cc
  • 代码有点乱,但我明白。它把它放到stackoverflow中。大家不要气馁,一切都会好的。以后提问的时候尽量贴sn-ps。例如,我会发布 while 循环并询问为什么它不起作用,而不是整个程序。继续编码,你做得很好!

标签: c++ random


【解决方案1】:

我查看了您的代码并对其进行了相当多的重构。这是它的 repl.it https://repl.it/JS45/0

我对您的代码所做的事情感到非常困惑,无法真正查看问题所在,但我确实使用了您想要的样式。

我将 GenRandom 函数更改为 GenRandomWord(length),而不是使用 while 循环,而是使用了 for 循环,这样更容易看出它将运行多长时间

我也只是打印出字符而不是将其保存到文件中。我相信你可以弄清楚如何做到这一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2011-05-18
    • 2014-12-15
    • 1970-01-01
    • 2013-10-21
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多