如何使while循环只运行特定次数

How to make a while loop run specific number of times only?

本文关键字:运行 何使 while 循环      更新时间:2023-10-16

我试图只将一定数量的单词推回到向量中,但

while (cin >> words) {
        v1.push_back(words);
    }

循环不会结束。下一个语句是将所有内容转换为大写。但它不会脱离while循环。连续不断地要求输入新词。

不要一下子就把所有事情都做完。您刚才描述的是一个for循环。只需读取输入所需的次数和每次迭代的push_back()。当for循环达到条件时,循环按预期结束。

// Here I create a loop control (myInt), but it could be a variable
// from anywhere else in the code. Often it is helpful to ensure you'll 
// always have a non-negative number. This can done with the size_t type.
for(std::size_t myInt = 0; myInt < someCondition; ++myInt)
{
    // read the input
    // push it back
}

请记住,当使用以循环控件为索引的for循环时,C/C++使用基于零的容器,如=>myContainer[myInt]

一个简单的方法是定义一个常量(例如size_t const MAX_WORDS = 3;),并检查v是否有足够的元素:

while ((v1.size() < MAX_WORDS) && (cin >> words))
{
    v1.push_back(words);
}