【发布时间】:2018-11-13 00:09:30
【问题描述】:
我试图弄清楚如何阻止用户两次或多次输入相同的输入。例如,程序要求用户输入 3 个输入,而不是相同的输入。但是现在我的程序仍然继续选择相同的输入。如果用户输入B2 3 次,则选择它 3 次。输出将是You have chosen these lots: B2 B2 B2,这应该是不可能的。
我的输入是数组顺便说一句。 code[3].
我希望它能够读取之前相同的输入并说它已经被选中,选择另一个作为输入。
我更喜欢使用strcmp。
#include <iostream>
#include <iomanip>
#include <string.h>
#include <fstream>
#include <conio.h>
char code[3][10];
for(int a=0; a<3; a++)
{
do
{
cout << "Please enter the lot you are interested in (A1-A7 / B1-B7): ";
cin >> ws;
cin.getline(code[a], 10);
if((strcmp(code[a], "A4") == 0) || (strcmp(code[a], "A6") == 0) || (strcmp(code[a], "B1") == 0)))
{
cout << "ERROR: Sorry! The house you chose has already been booked! \n\n"; // this are for booked lots already from the system
}
else if((strcmp(code[a], "A1") == 0) || (strcmp(code[a], "A2") == 0) || (strcmp(code[a], "A3") == 0) ....
{
cout << "SUCCESS: You have chosen the LOT " << code[a] << endl << endl;
}
else
{
cout << "ERROR: Sorry! The lot you entered is unavailable!" << endl << endl;
// i added strcpy(code[a], "A4"); to trick the system, and it works out.
}
}while((strcmp(code[a], "A4") == 0) || (strcmp(code[a], "A6") == 0) || (strcmp(code[a], "B1") == 0));
}
【问题讨论】:
-
请edit您的问题并附上您的代码。
-
好吧编辑了,@anatolyg
-
将字符串放入
std::set<std::string>。虽然集合的大小小于n,但请阅读另一个答案。当集合包含一个答案时,不要接受它。 -
请添加您对
code的定义/声明。您在文本中添加了code[3],但将其放入代码中会更清楚。是string code[3]吗?我试图猜测;更好地防止人们猜测,并发布您的完整代码。包括和#include <whatever>,等等。见minimal reproducible example。 -
使用
std::string比使用字符数组更容易。例如,您可以使用operator==与std::string进行比较。