如何使while循环只运行特定次数
How to make a while loop run specific number of times only?
我试图只将一定数量的单词推回到向量中,但
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);
}
相关文章:
- 花括号使循环运行一次?
- 如何使特定程序仅从安装的路径运行以避免DLL劫持
- 使 C++ Pi 近似在 GPU Nvidia 970M CUDA 上的 Paralell 中运行
- scanf() 的宽度说明符 - 要使用的字符长度在编译时不固定,仅在运行时确定.如何使其可变?
- 如何使visual studio代码直接运行vcvarsx86_arm64.bat而不是vcvarsall.bat
- 如何使线程运行现有类的函数?C++
- 分离线程然后让它超出范围(并使其仍在运行)是否安全?
- 如果输入变量的数据类型与以前不同,如何使我的循环仍然正常运行?
- 如何使功能"run"工作。程序在调用运行时退出
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 在构建之前,如何使Cmake在构建之前运行Python脚本,以生成用于构建中的项目的文件
- C 是否有办法使程序运行,只要引入了新值
- 如何使特定的部分功能运行并返回主循环
- 如何使用于 catch2 测试和项目运行的 cmake 目标更具可扩展性和合理性?
- 使Visual Studio的CMake工具在构建解决方案时运行INSTALL
- 如何使步进电机运行,直到我按下 Arduino 上的特定键盘按钮
- LD_BIND_NOW可以使可执行文件运行得更慢?
- 矩阵乘法 - 如何使行星绕自己的轴旋转,并绕其母轴运行?
- 有哪些优化技巧可以使我的代码运行得更快
- 使 C 代码能够作为C++代码运行