【问题标题】:Check if the user input has entered a repeated number检查用户输入是否输入了重复的数字
【发布时间】:2020-04-30 01:34:39
【问题描述】:

所以我仍然是这方面的初学者并且仍在练习。基本上我需要制作一个程序,继续要求用户输入除 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();

}

【问题讨论】:

  • 你显示的程序有什么问题?请花一些时间阅读有关how to ask good questionsthis question checklist 的信息。
  • 嗨 Raitik,我不明白你的问题。如果明确要求用户不要输入5,他将如何输入?循环应该在 5 次迭代后结束吗?那么输入5个数字后呢?然后只需检查计数器,即i 的值
  • cplusplus.com/forum/articles/12974 对不起,我之前没有添加它,我正在做 While(user == gullible),我被困在它的最后一部分。
  • 混合 conio.h 和 std::cin 可能会引起麻烦。 conio.h 也来自 80 年代,专为 MS-DOS 文本模式设计,在今天不是很有用(仅适用于玩具程序)。

标签: c++ loops if-statement input output


【解决方案1】:

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

★★ 修改程序,使其要求用户输入除被要求输入数字的次数以外的任何数字。 (即在第一次迭代中“请输入除 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";
}

【讨论】:

  • 为什么要使用逗号?
  • 我正在使用任何运算符,因为它很有用。为什么要专门询问运营商 , 而不是 &lt;++== 或其他什么?
  • operator , 不是微不足道的(此外,还有运算符优先级)。 if (num == i) { cout &lt;&lt; "Hey! you weren't supposed to enter " &lt;&lt; i &lt;&lt;"!\n"; return 0;} 似乎更简单。
【解决方案2】:

您可以将所有输入的数字添加到向量中,并且每当您获得一个新数字时,检查它是否已经在向量中。包括这些标题:

#include <vector>
#include <algorithm> // for std::find

像这样制作矢量

std::vector<int> pastEntries;

这样检查:

if (std::find(pastEntries.begin(), pastEntries.end(), num) != pastEntries.end()) {
    std::cout << "\nWhy did you enter " << num << "? :) " << endl;
    ...

当没有找到数字时,像这样将它添加到向量中(你可以把它放在if 块之后):

pastEntries.push_back(num);

或者,您可以使用std::set

std::set<int> pastEntries;

像这样插入到集合中:

pastEntries.insert(num);

然后像这样在集合中找到数字:

if (pastEntries.find(num) != pastEntries.end()) {

或者插入数字,同时找出是否已经插入,这样:

if (!pastEntries.insert(num).second) {

【讨论】:

  • std::set 似乎更合适。
  • if (!pastEntries.insert(num).second) /*Already inserted*/if (pastEntries.Count(num) != 0) {/*Already present*/}.
猜你喜欢
  • 2013-05-31
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 2023-03-27
  • 2019-03-09
相关资源
最近更新 更多