Recent

Author Topic: illegal expression  (Read 3548 times)

segfault

  • Full Member
  • ***
  • Posts: 107
illegal expression
« on: August 14, 2018, 04:33:01 pm »
I want to replace the last character in the string '012' by the value of i, which is a byte variable, but I'm getting an "illegal expression" error. Not sure why.

Code: Pascal  [Select][+][-]
  1. var
  2.   st  : string;
  3.   i   : byte;
  4. begin
  5.   st := '012';
  6.   i := 4;
  7.   str(i, st[length(st)]);
  8. end.

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: illegal expression
« Reply #1 on: August 14, 2018, 05:01:40 pm »
Str takes a var string variable as its second parameter (not a character, as you tried to give it).
Code: Pascal  [Select][+][-]
  1. var
  2.   st, newSt: String;
  3.   i: byte;
  4. begin
  5.   st := '012';
  6.   i := 4;
  7.   Str(i, newSt);
  8.   st := Copy(st, 1, 2) + newSt;
  9.   WriteLn('"',st,'"');
  10.   ReadLn;
  11. end.

segfault

  • Full Member
  • ***
  • Posts: 107
Re: illegal expression
« Reply #2 on: August 14, 2018, 05:27:05 pm »
D'oh!

Thanks. Actually the length of st varies so I need to modify your code slightly :

Code: Pascal  [Select][+][-]
  1. var
  2.   st,
  3.   s   : string;
  4.   i   : byte;
  5. begin
  6.   st := '0310';
  7.   i := 4;
  8.   str(i, s);
  9.   st := copy(st, 1, length(st)-1) + s;
  10.   writeln(st)
  11. end.

wp

  • Hero Member
  • *****
  • Posts: 11916
Re: illegal expression
« Reply #3 on: August 14, 2018, 06:29:32 pm »
I get the impression that "i" should always represent a numeric digit ('0' to '9'). Then you can also do this:
Code: Pascal  [Select][+][-]
  1.   st[Length(st)] := char(ord('0') + i);
If the input string is UTF8 encoded you must make sure that it has a single-byte code point at the end (i.e. < 128).
« Last Edit: August 14, 2018, 09:13:41 pm by wp »

 

TinyPortal © 2005-2018