Varo
Varo

Reputation: 1

Given a word or set of characters how to only take one part and dispose the rest

I use Free Pascal where I have to do a task for college course (introduction course to programming). We are not allowed to use certain words from Free Pascal like string, break, and some other ones hence my var for character is char.

Basically I need to take each letter from a word (or set of characters) and do something (in this case add the ASCII value to a number that is increasing each time I add a letter).

I am not able to stop the while loop when we find the first dot (.). Ideally if the user enters house.dog. I need the while to do the job only of the letters h, o, u, s, and e (the ones before the first .) and dispose the rest of the text “after the .” as will not be used

I have read that there is some internal difference between Read and ReadLn but could not figure out if that could be affecting the code and the error I get

I tried this code below and do not stop after I enter my word. Keep letting me adding words until I got Runtime error

program testingw;
var 
  myText : char;
  myResult : Integer;

begin
  writeLn ('enter your text');
  readLn (myText);

  while myText <> '.' do
  begin
    Read(myText);
    if myText <> '.' then
    begin
      myResult := myResult * 125 + ord(myText);
      WriteLn (myText);
    end;
  end; { while }
end.

Upvotes: 0

Views: 231

Answers (1)

Tom Brunberg
Tom Brunberg

Reputation: 21033

First a comment on variable naming: A var named myText gives me a mental picture of text of at least several sentences. Doesn't seem to fit well for only a character. myChar would be logical choice for a character.

Replace

  writeLn ('enter your text');
  readLn (myText);

with

  writeLn ('enter your text');
  read(myText);    // execution remains here until [Enter],
                   // entered chars are stored in input buffer
                   // myText refers to first char in buffer

and the while loop with

  while myText <> '.' do
  begin
    myResult := myResult * 125 + ord(myText);
    write(myText);
    read(myText);  // Fetch next char in buffer
  end;

Note however, that this is tested with Delphi. I can't verify with FP at the moment.

Upvotes: 1

Related Questions