C++:跟踪代码中的迭代(n次迭代后执行x)/用户输入
C++: Tracking iterations in code (after n iteration do x) / User input
我有一个关于我正在做的初学者作业的问题。最初的作业要求我制作一个程序,要求用户输入5以外的任何数字,直到用户输入5。如果他们输入5,程序将提醒他们输入5。任务的下一部分要求我设定一个条件,在10次迭代或10次非5值输入后,程序向用户发送消息并退出程序。我完成了第一部分,但第二部分有问题。我搜索了stackoverflow,发现了一些关于"get"函数的内容,但我不确定如何正确实现它。我将如何跟踪输入或迭代的数量,并确定在n次成功迭代后程序退出的条件?
此外,如果用户输入一个字符而不是整数,程序将警告用户并退出,我该如何设置条件?
谢谢你的帮助。这是我迄今为止写的代码。
// This program works, however, if user inputs a character or a very large number
//then the program malfunctions.
// Learn more about the get function.
#include <iostream>
using namespace std;
int main()
{
int inpt;
cout << "Please input any number other than 5.n";
cin >> inpt;
while (inpt != 5)
{
cout << "Please input another number other than 5.n";
cin >> inpt;
}
if (inpt = 5)
{
cout << "Hey! You weren't supposed to enter 5!";
}
return 0;
}
您需要添加一个计数器
int count = 0;
每次循环时递增
cout << "Please input another number other than 5.n";
cin >> inpt;
count++;
如果计数过大则停止
if(count>10) break;
你也可以改变你的飞行条件
备注if(inpt = 5)
不按你的想法行事,你的意思是inpt == 5
相关文章:
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 从 std::vector 迭代器中执行函数指针
- 如何仅在父循环的所有迭代都为真时才执行嵌套的 if 语句?
- 如何强制循环执行另一次迭代到零并关闭循环
- 如果我在下面的代码中使用 list 而不是 vector,为什么在我尝试在迭代器之间执行减法的行中编译失败?
- 在每次循环迭代时停止代码执行毫秒
- 访问执行策略for_each函数对象中的迭代器
- 先前循环迭代对当前迭代执行时间的影响
- std :: filesystem :: recursive_directory_iterator在可执行文件本身上迭代
- cmake:如何迭代目录中的所有源文件并将每个文件构建到可执行文件中
- 使用迭代器执行对象操作的函数
- 在向量和映射上执行擦除(迭代器)时观察到的不同行为
- 如何在迭代后重复从主函数重复执行
- while(getline(myReadFile, temp, ':')) 执行一次迭代太多导致向量越界
- 在我的switch语句完全执行之前,我的while循环进入第二次迭代,我用c ++编码
- 强制QBENCHMARK执行多次迭代
- 在执行 DFS 时在 Boost::graph 中维护迭代器
- 无法在 C++ 中执行迭代的 for 循环
- Cin未能在循环的第一次迭代后执行
- 为什么在第三个文件之前写入两个文件,即使指令是每次迭代执行每个文件