如何解决在不使用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
放入阵列中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。