C++:跟踪代码中的迭代(n次迭代后执行x)/用户输入

C++: Tracking iterations in code (after n iteration do x) / User input

本文关键字:迭代 执行 输入 用户 跟踪 代码 C++      更新时间:2023-10-16

我有一个关于我正在做的初学者作业的问题。最初的作业要求我制作一个程序,要求用户输入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