【问题标题】:Prevent element duplication without using std::vector and its features在不使用 std::vector 及其特性的情况下防止元素重复
【发布时间】:2020-08-14 02:31:36
【问题描述】:

我有一个程序要求用户输入 ID 和名称。但是,该 ID 必须是唯一的,以便用户可以继续输入姓名,否则程序必须不断提示用户输入唯一 ID。

问题是,尽管用户输入了一个唯一的字符串,但程序仍然不断提示用户输入ID,因此输入名称的代码永远不会执行。

#include <iostream>

int main() {
    std::string ID = {};
    std::string copy[3] = {};
    std::string name = {};
    bool isDuplicated = false;

    for (int i = 0; i < 3; ++i) {
        std::cout << "Enter details for student " << i + 1 << ": " << '\n';
        tryAgain:
        std::cout << "Enter ID: ";
        std::cin >> ID;

        // If ID is not duplicated,
        // continue to code of entering name. Otherwise,
        // keep prompting the user to enter a unique ID.

        for (int i = 0; i < 3; ++i) {
            if (i != 0)
                copy[i] = ID;

            if (copy[i] == ID) {
                isDuplicated = true;
                std::cout << "ERROR" << '\n';
            }
        }

        if (isDuplicated)
            goto tryAgain;

        else {
            std::cout << "Enter name: ";
            std::cin >> name;
            std::cout << '\n';
        }
    }
 
    return 0;
}

需要的输出(示例模拟):

Enter details for student 1:
Enter ID: 13
Enter name: Dog

Enter details for student 2:
Enter ID: 13 
ERROR: You already entered the ID!
Enter ID again: 17    
Enter name: Cat

Enter details for student 3:
Enter ID: 21
Enter name: Mouse

我的程序输出什么:

Enter details for student 1:
Enter ID: 13
ERROR: You already entered the ID!
ERROR: You already entered the ID!
Enter ID: 17
ERROR: You already entered the ID!
ERROR: You already entered the ID!

请注意,我们不能使用 std::vector 及其特性,这是我们需要坚持自己编写的算法的原因。

感谢任何帮助。非常感谢!

【问题讨论】:

  • 不相关:goto 很难搞定。如果你这样做了,就更难说服人们这是正确的。重写代码以使用循环和普通旧函数几乎总是比保护goto 的最佳用途所花费的时间更少。在这里,do/while 循环似乎是一个合适的替代品。
  • 即便如此,一旦你做对了并说服代码审查它是正确的,代码维护者要么:恨你,要么把它搞砸并在以后造成错误。
  • 尝试代码演练。或者使用调试器单步执行。有多个与您的症状相关的问题(我发现三个阅读代码;可能还有更多),这可能使这个问题对于 SO 来说过于宽泛。当您单步执行代码时,我建议您首先关注为什么每个 ID 会出现两个“错误”行,而您的意图是只得到一个。

标签: c++ arrays algorithm


【解决方案1】:
copy[i] = ID;

绝对保证

if (copy[i] == ID) 

会找到重复的。

解决方案:在验证没有重复之前,不要将ID 放入数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2020-02-03
    • 2017-05-18
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多