这个随机字符串打印代码有什么问题?

What is wrong in this random string printing code?

本文关键字:什么 问题 代码 打印 随机 字符串      更新时间:2023-10-16

我试图将X(x =用户输入(数字打印到字符串数组(Alpha(的行中,如果该行中有"A",则应在该行中打印某些内容(字符串或随机数(,例如"此行具有"A"。我无法弄清楚我的代码中出了什么问题,就像代码中的这一行无法正常工作一样: (Alpha[dist(gen(] == Alpha[0](

它正在打印出("此行有"A"(在具有其他字符串字母(S,P C等(的行中

#include <climits>
#include <ctime>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
using namespace std;
int main() {
int num;
const int SIZE = 6;
cout << "How many iterations: ";
cin >> num;
string Aplha[SIZE] = {"A", "D", "P", "E", "C", "S"};
random_device randNum;
mt19937 gen(randNum());
uniform_int_distribution<> dist(0, 5);
uniform_int_distribution<> distRange(INT_MIN, INT_MAX);
for(int i = 0; i < num; i++) {
cout << Alpha[dist(gen)];
if(Alpha[dist(gen)] == Alpha[0]) {
cout << " this line has A " << distRange(gen);
}
cout << endl;
}
return 0;
}

结果应该是...

如果一行有"A",则:

A this line has A 123231315
D
P
D
S
A this line has A 845421541
C

我得到的结果是这样的...

How many iterations: 10
S
S this line has A 1950029843
S
C this line has A -145672138
A
C
D
C
E
S

您打印的Alpha[dist(gen)]与您根据Alpha[0]检查Alpha[dist(gen)]不同。每次调用dist(gen)都会产生不同的随机数。

错误在接下来的两行中。每次调用dist(gen)时,都会得到不同的索引。

cout << Alpha[dist(gen)];   
if (Alpha[dist(gen)] == Alpha[0])

我想,它应该像风箱一样。

const size_t j = dist(gen);
cout << Alpha[j];   
if (Alpha[j] == Alpha[0])