如何创建一个循环,该循环检查每次迭代并在每次迭代后从头开始
how to create a loop that checks for each iteration and starts back at the beginning after each iteration
我想创建一个函数,通过使用随机数字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)) {
接下来,将break
s(脱离for
循环,结束它(更改为跳到循环末尾并继续的continue
s。
我认为还有其他问题,但这将使您朝着正确的方向开始。
相关文章:
- 擦除while循环中迭代的元素
- 对于set上的循环-获取next元素迭代器
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 将多个 for 循环组合成单个迭代器
- 为什么我的 scanf() 没有在我的数组上迭代我的 for 循环?
- 使用一个 for 循环如何迭代和测试迭代器值?
- 循环挂起迭代的 std::擦除 on std::list
- 使用基于范围的循环迭代矢量时出现问题
- 整个循环花费的时间比其迭代总和要长
- 为什么"i"在循环的每次迭代中都没有增加?(C++)
- 转到基于范围的 for 循环中的下一个迭代器
- C++:返回一个基于范围 for 循环迭代器,其中包含继承对象
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- C++ Code 在 for 循环期间不会累积变量中的总和,仅提供最终迭代值
- Visual Studio 2013 C 的迭代循环
- 矢量迭代循环引发错误
- C++:如何将数据从迭代循环输出到列中
- 迭代循环重复的次数比我预期的要多
- c++ 11线程在迭代循环时间
- 迭代循环与索引循环