0

I have a c++ program.I am using a do while loop to re execute the program after every cycle if the user chooses to run it again.The program runs fine on the first loop but on the subsequent runs the program skips requesting for a diver's name.It just prints the prompt for diver's name and number of judges together as shown below.How can i correct that?

On first run,notice the user is prompted to enter the number of judges after entering the diver's name as below

enter image description here

On the subsequent runs,the program does not wait for user to input the diver's name before requesting for the number of judges,it prints the two prompts together and only number of judges can be input as shown below

enter image description here

And here is the main class which holds the logic of execution:

int main()
{
  char rerun;
  do{
      srand(time(NULL));           

      int number_of_judges=0;
      char option,dive;
      char dives[3];
      string divenames[3];

      double** scores; 

      string diverName="";
      cout<<"What is the diver's name? "<<endl;
      getline(cin,diverName);

      number_of_judges=getjudges();

      cout<<number_of_judges;

      displayMenu();


      for(int i=0;i<3;i++){
          cout<<"Enter dive "<<i+1<<" to be judged(A-E)";
          cin>>dive;
          dive=tolower(dive);
          while(!(dive=='a' || dive=='b' || dive=='c' || dive=='d' || dive=='e' ) ){
              cout<<"You entered the wrong choice.Choice must be from (a-e)."<<endl;
              cout<<"Enter dive "<<i+1<<" to be judged(A-E)";
              cin>>dive;
              dive=tolower(dive);
          }
          dive=tolower(dive);
          dives[i]=dive;
      }

      for(int i=0;i<3;i++){
          divenames[i]=getDive(dives[i]);
      }

      scores=getRandom();
      getScores(diverName,scores,divenames);

      cout<<"Do you want another try?";
      cin>>rerun;

      while(rerun !='y' && rerun!='n'){
          cout<<"You have entered an invalid option.\nPlease try again.";
          cin>>rerun;
          rerun=tolower(rerun);
      }

  }
  while(rerun=='y' || rerun == 'Y');
  std::getchar();
  return 0;
}

Any help will be greatly appreciated.

Eric Fortin
  • 7,323
  • 2
  • 23
  • 31
mungaih pk
  • 1,715
  • 8
  • 27
  • 56

1 Answers1

0

In the line:

cin>>rerun;

a charachter is extracted from the stream. This operation, however, leaves a newline in the buffer. So, when in the next step, you do:

getline(cin,diverName);

you are trying to read all the input up to newline and in the buffer there is already a newline (coming from the previous step): then this operation ends immediately.

The solution is to add an instruction after cin>>rerun of this type:

cin.ignore();

in this manner the newline left in the buffer will be discarded in the next operation.

Waldir Leoncio
  • 9,134
  • 14
  • 68
  • 94