如何创建一个循环,该循环检查每次迭代并在每次迭代后从头开始

how to create a loop that checks for each iteration and starts back at the beginning after each iteration

本文关键字:迭代 循环 何创建 从头开始 检查 一个 创建      更新时间:2023-10-16

我想创建一个函数,通过使用随机数字gen选择1或2,然后在字符串中的单词之间随机插入一个空格,然后继续插入或跳到下一个单词的结尾。 我希望这只发生在字符串的长度小于我使用变量 myLength 设置的预定义限制时。 我的主要问题是我设计不佳的循环填满了第一个单词和第二个单词之间的空间,并且不检查其他单词。

我的主要问题是我设计不佳的循环填满了第一个单词和第二个单词之间的空间,并且不检查其他单词。

void NumLoop(string& s) {
int pos = s.find_first_of(' ');
while (s.length() < myLength) {
for (int pos; pos != string::npos; pos = s.find(' ', pos + 1)) {
int choice = rand() % 2;
if (choice = 1) {
s.insert(pos + 1, " ");
break;
}
if (choice = 0) {
break;
}
}
}
cout << s;
system("pause");

}

我希望程序随机选择单词之间的空格,然后增加字符串大小,直到达到所需的 s.length。

首先,这个pos

int pos = s.find_first_of(' ');

for循环的范围内被以下pos隐藏:

for (int pos; pos != string::npos; pos = s.find(' ', pos + 1)) {

因此,摆脱第一个并将两者结合起来,如下所示:

for (int pos = s.find_first_of(' '); pos != string::npos; pos = s.find(' ', pos + 1)) {

接下来,将breaks(脱离for循环,结束它(更改为跳到循环末尾并继续的continues。

我认为还有其他问题,但这将使您朝着正确的方向开始。