我有一个程序,提示用户输入一个值。用户输入的每个值都放入一个向量'other'中,这个值只用于验证。如果输入了重复值,则用户将得到一个提示,直到他们输入唯一值。防止重复进入矢量? C++
我面临的主要问题是,由于某些原因,在运行代码并打印出矢量结果时,似乎有重复条目。谁能告诉我为什么?
请参阅以下我的代码:
// prompt to continue
cout << "Would you like to continue? [Y]es, [N]o: ";
cin >> toContinue;
while (toContinue == 'Y')
{
bool isDuplicate = 0;
// prompt for product no.
cout << "Please enter product number: ";
cin >> productB;
// Validation check for duplicate entries
for (size_t i = 0; i < other.size(); i++)
{
if (productB == other[i])
isDuplicate = 1;
while (isDuplicate == 1)
{
cout << "You have already entered this product number!" << endl;
cout << "Please enter correct product number: ";
cin >> productB;
if (productB != other[i])
other.push_back(productB);
isDuplicate = 0;
}
}
// prompt to continue
cout << "Would you like to continue? [Y]es, [N]o: ";
cin >> toContinue;
}
改为使用'std :: set'。 – user0042
你可能想用调试器来浏览你的程序。提示:当我输入'3 4 3'时会发生什么? – Rakete1111
检测到重复项目后,您要求用户重新输入。您可以根据之前输入的一个号码检查此新号码,但不能对所有先前输入的号码进行检查。所以说,用户再次输入“1”,然后输入“2”,然后输入“1”。您检测到重复并要求重新输入。他们输入'2',你只检查'2!= 1',并愉快地将第二个'2'加到向量中。 –