我有一个程序会询问学生姓名和他/她的 10 个类(class)。该代码应该防止重复条目,但每次我运行该程序时,它都会说每个条目都已存在。我已经经历过这件事一千次了,但我一生都无法弄清楚。任何对我的问题的见解将不胜感激。
#include <iostream>
using namespace std;
struct student
{
string name;
string classes[10];
};
int main(int argc, char *argv[])
{
string test_name;
student entry;
cout << "Enter the name of the student you wish to insert (string) \n";
cin >> entry.name;
for(int i = 0; i < 9; i++)
{
cout << "Enter class number " << i + 1 << " For " << entry.name << endl;
cin >> test_name;
for(int j = 0; j < 9; j++)
if(test_name == entry.classes[j])
{
cout << "Class already exists for " << entry.name << ". Please try again.\n";
i -= 1;
}
else
{
entry.classes[i] = test_name;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
最佳答案
您的内部 for
循环测试所有 10 个位置,包括您要插入新类的位置。
您确实只想扫描填充的位置,查看是否有任何匹配项,然后,在循环之外,添加新类(如果它不重复)。
伪代码:
for (i = 0; i < 10; i++)
{
get class 'i';
bool repeat = false;
for (j = 0; j < i; j++) // Only check previous classes (j < i)
if (test_name == entry.classes[j])
{
repeat = true;
break;
}
if (repeat)
{
output the error
rewind 'i'
continue;
} else
{
insert the new entry
}
}
关于c++ - 嵌套循环语句结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19738593/