我想在给定的行中提取一个随机数,因此我调用了一个随机数以将其用作索引。但这总是给我一个错误。
terminated called after throwing an instance of 'std::out_of_range'.
我知道这是因为索引值超出了字符串的大小。但是我在代码中找不到任何错误。
do {
int size = line.length();
srand(time(NULL));
index = rand() % size;
} while (isspace(line.at(index)));
这是一个随机数生成器。我从文本文件中提取一行。
我用过做{} while(isspace(line.at(index)));因为我不希望它是空格,所以如果它是空格,为了再次生成一个随机数。
我想要的是这个。
0123456789
示例...索引:4
F --- i ---- L F:第一,L:最后
if (index == 0) {
while (!isspace(line.at(last + 1))) {
last = last + 1;
}
}
else if (index == (size - 1))) {
while (!isspace(line.at(first - 1))) {
first = first - 1;
}
}
else {
while (!isspace(line.at(first - 1))) {
first = first - 1;
}
while (!isspace(line.at(last + 1))) {
last = last + 1;
}
}
for (int i = first; i <= last; i++) {
targetword += line.at(i);
}
这是我计算第一个和最后一个索引并打印出所选单词的方式,它应该不会出现任何错误...
请帮助我,谢谢