我是 C++ 新手。我想生成要在我的程序中使用的随机字符串序列。它大部分时间都有效,但偶尔会出现异常并从计算机内存中转储随机字符串。我犯了什么愚蠢的错误(如果有的话)?
代码如下:
#include <iostream>
#include <ctime> // Needed for the true randomization
#include <cstdlib>
#include <string>
using namespace std;
int main ()
{
string holder[] = {"A", "B", "C", "D", "E"};
int xRan;
srand(time(0)); // This will ensure a really randomized number by help of time.
xRan=rand()%6+1;
xRan--;
cout << "Value of xRan is: " << xRan << " value is " << holder[xRan] << endl;
return 0;
}
最佳答案
您的 xRan 计算为您提供了 1 到 6 之间的数字。您的数组有 5 个元素,它们的编号为 0 到 4。
将 xRan=rand() % 6 + 1;
更改为 xRan=rand() % 5;
,然后删除递减 的下一行>xRan
。这将为您提供 0 到 4 之间的数字,这就是您想要的。
关于c++ - 简单的 C++ 程序超出其数组边界并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22509224/