嵌套循环语句结果不正确
Nested loop statement incorrect results
我有一个程序,它会询问一个学生的名字和他/她的10个班级。代码应该防止重复条目,但每次我运行程序时,它都说所有内容都是每个条目都已经存在。这件事我已经经历了一千次,一辈子都想不通。对我的问题的任何见解将不胜感激。
#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
}
}
虽然这是在 Java 中,但您可以做类似的事情,我认为它满足了忽略类数组中已有的任何输入并添加它的要求,如果直到达到 10 个类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) throws IOException {
ArrayList < String > classes = new ArrayList < String > ();
System.out.println("Enter the name of the student you wish to insert (string) n");
while (classes.size() < 10) {
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System. in ));
String s = bufferRead.readLine();
for (String classy: classes) {
if (classy.equals(s)) {
System.out.println("This is duplicate class");
break;
}
}
classes.add(s);
}
System.out.println("Ten Classes have been input");
}
}
要真正看到,出了什么问题,请在您的if()
语句之前添加以下行:
cerr << "test_name == "" << test_name << "", entry.classes[j] == "" << entry.classes[j] << ""n"
我期望,你看到的是,由于某种原因,test_name是空的,我知道所有未初始化的字符串都会显示为空字符串。但是,无论出了什么问题,上面的一行都应该显示出来。
相关文章:
- 密码登录程序将永远循环并显示不正确的结果
- 特征 LLT 模块给出不正确的结果?
- 计算幂级数的数学结果不正确
- wcslen() 在使用编译指示包时返回不正确的结果
- 使用动态分配的数组进行矩阵乘法;结果不正确
- CMake 查找特征不正确的结果
- 将函数的地址转换为UINTPTR_T给我不正确的结果
- 使用 C++ 中的运算符重载显示不正确的结果
- 简单的程序比较阵列运行但给出不正确的结果
- 在运行libtorch的模型时获得的结果是不正确的,该模型经过训练并从Pytorch出口
- 当我输入分数值时,它返回不正确的结果
- time_t提高日期转换,给出不正确的结果
- 为什么隐式类型转换在此代码中结果不正确
- 排序向量不断修改数据并打印不正确的结果
- 使用Boost Polygon的减法结果不正确
- 脑解释器在C++产生不正确的结果
- 具有OFN_ALLOWMULTISELECT不正确的快捷方式结果的 CFileDialog
- 递归阶乘函数在"22!"上产生不正确的结果
- GLM 矩阵乘法向量给出不正确的结果
- 浮点数和由于舍入行为导致的不正确结果