本文介绍了陷入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

noob程序员在这里.如果我提供的信息不够高级,请上大学的第一门CS课,并在此处发布第一篇帖子.

noob programmer here. Taking my first CS class in college and making first post on here so excuse me if the info i provide is not sufficient in advanced.

仍然试图找出循环.似乎可以理解,但是一旦循环中存在循环或者循环中是否存在语句,我就会被抛弃并且不知道如何进行.对于我的任务,我需要进行以下操作.

Still trying to figure out loops. Seem to get it but once there is loops within loops or if statements inside loops, I get thrown off and have no idea on how to proceed. For my assignment, I need the following to occur.

您要处理文件中的所有记录吗?(y/n)宽请输入y或n.您要处理文件中的所有记录吗?(y/n)n输入要处理的记录数:两个XXXXXXXXXX错误-非数字或负值,请重试输入要处理的记录数:10

Would you like to process all the records in the file? (y/n) WPlease enter either y or n.Would you like to process all the records in the file? (y/n) nEnter number of records to process: twoXXXXXXXXXX Error-non numeric or negative value, try againEnter number of records to process: 10

这是我的代码:

char a = 0;             //User chooses Y or N
int ProcessAmount = 0;  //Amount of times to process if not all

  cout << "Would you like to process all the records in the file? (y/n) ";
  cin >> a;

  do{

    bool notDone = true;

      if(a  == 'n'){
        while(notDone){
              cout << "Enter records to process: ";
              cin >> ProcessAmount;

              if (cin.fail()){
                  cin.clear();
                  cin.ignore(40,'\n');
                  cout << "" << endl;
              }
              else{
                  notDone = false;
              }
        }
      }else if(a != 'y' or a != 'n');
            cout <<"Please enter either y or n." << endl;

  }while( a != 'y');

推荐答案

大多数问题都在评论中解释,我将如何解决:

Most problems are explained in comments, here is how I would fix it:

char a = 0;             //User chooses Y or N
int ProcessAmount = 0;  //Amount of times to process if not all

cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;

while (a != 'y') {

  bool notDone = true;

  if(a  == 'n'){
    while(notDone){
      cout << "Enter records to process: ";
      cin >> ProcessAmount;

      if (cin.fail()){
          cin.clear();
          cin.ignore(40,'\n');
          cout << "" << endl;
      } else {
        notDone = false;
      }
    }
  } else if(a != 'y' or a != 'n') {
    cout <<"Please enter either y or n." << endl;
    cin >> a; // Need to get new input because old one is invalid.
  }

};

我也看不到如何使用 notDone .我也强烈建议使用适当的缩进,在关键字周围使用空格,如 while for if else 这是很好的风格.

Also I don't see how notDone is used. Also I would strongly advise of using proper indentation, spaces around keywords as while, for, if, else as it is good style.

这篇关于陷入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:28