c++ - 在不使用 std::vector 及其特性的情况下防止元素重复
问题描述
我有一个程序要求用户输入 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 及其特性,这是我们需要坚持使用自己编写的算法的原因。
任何帮助表示赞赏。非常感谢!
解决方案
copy[i] = ID;
绝对保证
if (copy[i] == ID)
会找到重复的。
ID
解决方案:在验证没有重复之前不要放入阵列中。
推荐阅读
- plugins - HTML 显示在地图选项卡的前端
- sql - SQL 参数为空时全选
- java - 使用 Heroku 使用 Maven 构建应用程序时出错
- java - Alexa 自定义技能未将项目插入 DynamoDB
- matplotlib - 如何使用地理数据框中的第一行在图形上创建文本框?
- node.js - 请求的资源上不存在“Access-Control-Allow-Origin”标头。NODE-server,我已将原点应用于 Cors
- c++ - 使用抽象类 C++ 单独编译
- css - 为什么 scrollbar-color 属性不能直接在 body 上工作?
- asp.net-mvc - 为什么我的 ASP.NET MVC 表单不会回传到我的控制器
- javascript - v-show 在 v-for 循环中,我只需要打开单击的选项