C ++随机ID和随机答案

时间:2018-11-22 19:25:40

标签: c++ char

我正在编写一个程序,该程序输出一个ID和答案的随机猜测。 您可以猜测A,B,C,D,并且ID的前2个字母为随机字符,后3个为数字。

  

错误是程序给了我这样的ID:YN420BBBBCBACDBBCDB

您可以在其中清楚地看到ID。但是,它将随机答案和它的变量放在一个变量中。这是我的代码:

        #include <iostream>
        #include <stdio.h>
        #include <ctime>
        #include <cstdlib>
        #include <string>
        #include <fstream>

        using namespace std;

        char id[6];
        char answers[16];

        int main()
        {
            srand(time(NULL));
            int random =rand() % 500+1;
            const char* const a_to_d       = "ABCD"                       ;
            const char* const a_to_z       = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
            const char* const zero_to_seven = "01234567";

            for (int i = 0; i < random; ++i){
            int ri = rand()  % 26;
            id[0] = a_to_z[ri];
            int ri1 = rand() % 26;
            id[1] = a_to_z[ri1];

            int ri2 = rand() % 7;
            id[2] = zero_to_seven[ri2];
            int ri3 = rand() % 7;
            id[3] = zero_to_seven[ri3];
            int ri4 = rand() % 7;
            id[4] = zero_to_seven[ri4];
            id[6] = 0;
            cout<<id<<"     "<<answers<<endl<<endl;

            int fi   = rand() % 4;
            answers[0]  = a_to_d[fi];
            int fi1  = rand() % 4;
            answers[1]  = a_to_d[fi1];
            int fi2  = rand() % 4;
            answers[2]  = a_to_d[fi2];
            int fi3  = rand() % 4;
            answers[3]  = a_to_d[fi3];
            int fi4  = rand() % 4;
            answers[4]  = a_to_d[fi4];
            int fi5  = rand()  % 4;
            answers[5]  = a_to_d[fi5];
            int fi6  = rand() % 4;
            answers[6]  = a_to_d[fi6];
            int fi7  = rand() % 4;
            answers[7]  = a_to_d[fi7];
            int fi8  = rand() % 4;
            answers[8]  = a_to_d[fi8];
            int fi9  = rand() % 4;
            answers[9]  = a_to_d[fi9];
            int fi10 = rand() % 4;
            answers[10] = a_to_d[fi10];
            int fi11 = rand() % 4;
            answers[11] = a_to_d[fi11];
            int fi12 = rand() % 4;
            answers[12] = a_to_d[fi12];
            int fi13 = rand() % 4;
            answers[13] = a_to_d[fi13];
            int fi14 = rand() % 4;
            answers[14] = a_to_d[fi14];
            answers[16] = 0;
            }

            return 0;
        }

1 个答案:

答案 0 :(得分:1)

您的char数组需要以空值结尾。由于不存在,因此cout继续进入下一个数组,直到最终找到空终止符。要解决此问题,只需将长度增加一个char id[5]并将最后一个值设置为0 id[4] = 0

此外,您的模运算符将永远不会覆盖ri和ri2的最后一个值。 rand() % 25可获得的最大值是24。您实际上想要rand() % 26