Search code examples
averagepascal

Why can’t I enter a new name after my while loop is finished?


Why can’t I enter a new name after my while loop is finished? The loop should ask for a new name and it should until terminated, but it doesn’t do that. Why?

I was trying to create a program to read the student name and ID for a student as well as finding their average and finally outputting the ID and name with the title they relieved as a result of their average.

program Students_of_ABC_Highschool;

var 
ID:integer;
studentname:string;
Mathmark:integer;
ITmark:integer;
Englishmark:integer;
Chemistrymark:integer;
Spanishmark:integer;
Frenchmark:integer;
Averagemark:integer;


begin

Averagemark:= 0;
Mathmark:=0;
ITmark:=0;
Englishmark:=0;
Chemistrymark:=0;
Spanishmark:=0;
Frenchmark:=0; 


while Averagemark <101 do begin 

writeln (' Please enter a student name ');
read (studentname);

writeln ('Please enter students ID: ');
read (ID);

writeln ('Please enter Math mark ');

  read (Mathmark);
  writeln ('Please enter IT mark ');
  
  read (ITmark);
  writeln ('Please enter English mark ');
  
  read (Englishmark);
  writeln ('Please enter Chemistry mark ');
  
  read (Chemistrymark);
  writeln ('Please enter Spanish mark ');
  
  read (Spanishmark);
  writeln ('Please enter French mark ');
  read (Frenchmark);
  
Averagemark:= (Mathmark + ITmark + Englishmark + Chemistrymark + Frenchmark +
     Spanishmark) div 6;
  writeln (' Average mark for student is ', Averagemark);
  
  if Averagemark >=60 then begin
  
      writeln ('Congratulations you are invited to the award ceremony ',studentname);
  end
  else
    begin writeln ('You are encouraged to work harder ', studentname);

  end;
  end;
  end.

Solution

  • You are employing read instead of readLn. If you have a look into ISO standard 10206 “Extended Pascal”, you will find the following note:

    e) If v is a variable‑access possessing a fixed‑string‑type of capacity c, read(f, v) shall satisfy the following requirements. [… super technical mumbo jumbo …]

    NOTE — 6 If eoln(f) is initially true, then no characters are read, and the value of each component of v is a space.

    Bottom line, you can “fix” your program by inserting the following conditional readLn which will “consume” any “remnant” end‑of‑line character prior your actual read:

    writeln (' Please enter a student name ');
    if EOLn then
    begin
        readLn
    end;
    read (studentname);
    

    For the record: This is mostly a copy of an earlier answer of mine.