嵌套循环语句结果不正确

Nested loop statement incorrect results

本文关键字:不正确 结果 语句 嵌套循环      更新时间:2023-10-16

我有一个程序,它会询问一个学生的名字和他/她的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是空的,我知道所有未初始化的字符串都会显示为空字符串。但是,无论出了什么问题,上面的一行都应该显示出来。