首页 > 解决方案 > 检查用户输入是否输入了重复的数字

问题描述

所以我仍然是这方面的初学者,还在练习。基本上我需要制作一个程序,继续要求用户输入除 5 以外的任何数字,直到用户输入数字 5。

我已经完成了,但我不知道如何检查用户是否输入了重复的数字。例如:1 2 3 3 - 程序应该结束

#include <iostream>
#include <conio.h>
#include <iomanip>

using namespace std;

int main() {

cout << setw(15) << setfill('*') << "*" << endl;
cout << "Number 5" << endl;
cout << setw(15) << setfill('*') << "*" << endl;

int num;


cout << "Enter a number: ";
cin >> num;

if (num == 5) {
    cout << "\nWhy did you enter 5? :) " << endl;
    _getch();
    exit(0);
}
for (int i = 1; i < 10;i++) {

    cin >> num;

    if (num == 5) {
        cout << "\nWhy did you enter 5? :) " << endl;
        _getch();
        exit(0);
    }
}

cout << "Wow, you're more patient then I am, you win." << endl;
_getch();

}

标签: c++loopsif-statementinputoutput

解决方案


之前的答案不符合链接文章中的要求,提问者本人似乎没有掌握:

★★ 修改程序,使其要求用户输入除被要求输入数字的次数以外的任何数字。(即在第一次迭代中“请输入除 0 以外的任何数字”和在第二次迭代中“请输入除 1 之外的任何数字”等等。当用户输入他们被要求不输入的数字时,程序必须相应地退出至。)

此变体符合:

#include <iostream>
using namespace std;

int main()
{
    for (int i = 0; i < 10; i++)
    {
        cout <<"Please enter any number other than " <<i <<": ";
        int num;
        cin >>num;
        if (num == i)
            return cout <<"Hey! you weren't supposed to enter " <<i <<"!\n", 0;
    }
    cout <<"Wow, you're more patient then I am, you win.\n";
}

推荐阅读