Search code examples
charpascal

Pascal Counting the number of words in a line


I am trying to write a program that will count the number of words in each line. But the loop is not interrupted by a newline.

`

program StringSymbols;
var
   c  : char;
   i : integer;
begin
   i := 1;
   c := ' ';
   writeln('Enter your string');
 while c <> '#13' do
   begin
      read(c);
      if c = ' ' then i := i + 1;
   end; 
   writeln('count words: ', i)
end.

`

Please tell me how to write correctly. It is important that it was character-by-character reading.


Solution

  • The character literal #13 for Carriage-Return should not be placed inside apostrophes, as then you got a three letter string.

    read(c);
    while (c <> #13) and (c <> #10) do
    begin
        if c = ' ' then inc(i);
        read(c);
    end;