Recent

Author Topic: [Programming ] String to Numbers  (Read 4731 times)

apachetransfire

  • Newbie
  • Posts: 3
[Programming ] String to Numbers
« on: May 01, 2018, 07:26:07 pm »
Hello,

Sorry for my bad english , I'm French and this first and second semester we've learned programming with Freepascal.
We're asked , for exemple from a string like '5+13+8' to return the decimal resultat , which is in this case 26 .
I've managed to make a program and to compile it :

program interface1;

uses
   SysUtils;

Const MAX = 255;

Type
   Green = array[1..MAX] of String;
   
procedure classifier ( chaine : string; var g : green );

 var k : Integer;
   
 begin
      g[1] :='+';
       for k:=2 to length(chaine)+1 do
         g[k]:= Copy(chaine,k-1,1);
 end;
       
procedure nombreetsigne ( g : Green ; var nombre : Integer; var signe : string; var pos : Integer);

var sub : String;

begin
   signe := g[pos];
   sub :='';
   pos := pos +1;
   while ( (g[pos]<>'+') and (g[pos]<>'-')) do
     begin
     sub := sub+g[pos];
     pos := pos+1;
     end;
   nombre := StrtoInt(sub);
end;

function calculerresultat( chaine : string; g : Green ) : Integer;

var  pos , nombre , transit : Integer;
     signe : String;

begin
  transit := 0;
  pos := 1;
  while (pos <> length(chaine)) do
    begin
      nombreetsigne(g,nombre,signe,pos);
      if (signe ='+') then
        transit := transit + nombre;
      if ( signe ='-') then
        transit := transit - nombre;
    end;
  calculerresultat := transit; 
end;


var chaine : String;
       g : Green;
   
begin
    write('entrez votre calcul :');
    readln(chaine);
    classifier(chaine,g);
    writeln(calculerresultat(chaine,g));
end.

However , when trying to run it the following appears :

An unhandled exception occurred at $0000000000402941:
EAccessViolation: Access violation
  $0000000000402941
  $00000000004004B3
  $00000000004005E5

I've already searched in the forum and i know it is related to an acess to an invalid memory ( not created yet )
i'm pretty sure it has a link with the variable pos , in fact i want it to be considerer has an input and output for the procedure nombreetsigne

Thank you for your help!




marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 12712
  • FPC developer.
Re: [Programming ] String to Numbers
« Reply #1 on: May 01, 2018, 08:21:53 pm »
Such an example is included in the Free Pascal sources (fpc/packages/symbolic/examples)

e.g.

Code: Pascal  [Select][+][-]
  1. {$mode delphi}
  2. Uses Symbolic,Classes,sysutils;
  3.  
  4. var s : AnsiString;
  5.     a : extended;
  6.     b : integer;
  7.    
  8. begin
  9.   // quickevaluate('expression',[],[]); evaluates a constant expression to an
  10.   //  extended result
  11.  
  12.   s:='(5+5+10)*2';
  13.   writeln(s,'=',QuickEvaluate(s,[],[]):10:1);
  14.  
  15.  
  16.   // ... but still allows variables:
  17.  
  18.   a:=2.0;
  19.   b:=3;
  20.   s:='(5+A+10)*B';
  21.   // variable names are case sensitive!
  22.   writeln(s,'=',QuickEvaluate(s,['A','B'],[a,b]):10:1,' with A=',a:0:1,' and B=',b);
  23. end.

For more details see the symbolic unit sources.

bytebites

  • Hero Member
  • *****
  • Posts: 778
Re: [Programming ] String to Numbers
« Reply #2 on: May 01, 2018, 08:28:21 pm »
Just copy from Free Pascal sources and get 10 points.

Handoko

  • Hero Member
  • *****
  • Posts: 5524
  • My goal: build my own game engine using Lazarus
Re: [Programming ] String to Numbers
« Reply #3 on: May 01, 2018, 08:35:15 pm »
Hello apachetransfire,
Welcome to the forum.

Cool, you're now learning expression parsing. I'm a self-taught programmer, expression parsing was a very difficult thing for me to solve. I managed to create a simple expression parsing calculator but it was very limited. Until I read a senior posting a video tutorial in this forum many years ago, now I understand how it works.

To build a math expression parser, you need at least:
- Understand what infix and postfix notations are
- Know how to use stack

Here is the video tutorial:
https://www.youtube.com/watch?v=mHk2oquBHQg

They used Java in the tutorial, but you should able to understand the logic for parsing math expression.

Alternatively, you can use ready to use tool for solving the 'math string', like suggested by marcov or FPExpressionParser:
http://wiki.freepascal.org/How_To_Use_TFPExpressionParser#Defining_the_expression

apachetransfire

  • Newbie
  • Posts: 3
Re: [Programming ] String to Numbers
« Reply #4 on: May 01, 2018, 10:43:39 pm »
Thanks for the response,

In fact , in order to do my program , i'm only allowed to use three functions :
    - Copy , StrtoInt and length

I've tried to run my program once again and it works only for one digit numbers like :
   6-7+8-3
and it doesn't even take into account the last digit so it returns +7 (
but when i try with a two digit number like  6-7+28 it sends my an access violation

does the fonction StrtoInt works for two digit numers , like if i have '23' it will returns to me 23 ?

Thanks for the answers anyway

jamie

  • Hero Member
  • *****
  • Posts: 7600
Re: [Programming ] String to Numbers
« Reply #5 on: May 01, 2018, 10:56:44 pm »
Enable Range checking in your program..

{$R+}

 I see in one of your functions you are not checking to ensure "POS" is in range of the string..

The only true wisdom is knowing you know nothing

HeavyUser

  • Sr. Member
  • ****
  • Posts: 397
Re: [Programming ] String to Numbers
« Reply #6 on: May 01, 2018, 11:12:13 pm »
Thanks for the response,

In fact , in order to do my program , i'm only allowed to use three functions :
    - Copy , StrtoInt and length

I've tried to run my program once again and it works only for one digit numbers like :
   6-7+8-3
and it doesn't even take into account the last digit so it returns +7 (
but when i try with a two digit number like  6-7+28 it sends my an access violation

does the fonction StrtoInt works for two digit numers , like if i have '23' it will returns to me 23 ?

Thanks for the answers anyway
what does the classifier procedure suppose to do?

Bart

  • Hero Member
  • *****
  • Posts: 5706
    • Bart en Mariska's Webstek
Re: [Programming ] String to Numbers
« Reply #7 on: May 01, 2018, 11:44:18 pm »
What operators are you supposed to handle?
Do you need to take into account the order of operators (2+3*4=2+12=14, instead of 2+3*4=5*4=20)?

And yes: StrToInt('123') will give you the value 123 as a result.

Can you write out an algorithm that completes the task (don't use actual pascal, just describe the steps)?

Expression parsing is not a simple thing to do...

Bart

sam707

  • Guest
Re: [Programming ] String to Numbers
« Reply #8 on: May 02, 2018, 12:27:44 am »
@apachetransfire
t'as d'la veine qu'on te demande pas des opérations en chiffres romains mdr

algo
substr:=emptystr;
 for ptr := 1 to end of string-1 do begin
 while (not end of string) and (char[ptr] in ['0'..'9']) do begin
  substr := substr+char[ptr];
 ptr:=ptr+1;
 end while;
 intermediatevalue := strtoint(substr);
 ... do what you need with ...
 substr := emptystr;
end for.
« Last Edit: May 02, 2018, 12:33:41 am by sam707 »

apachetransfire

  • Newbie
  • Posts: 3
Re: [Programming ] String to Numbers
« Reply #9 on: May 02, 2018, 12:32:44 am »
Thanks for the replies

I've managed to fix the problem in my program ( it was just a build in issue )

here's the code :

program interface1;

uses
   SysUtils;

Type
   Green = array[1..255] of String;
   
procedure classifier ( chaine : string; var g : green );

 var k : Integer;
   
 begin
      g[1] :='+';
       for k:=2 to length(chaine)+1 do
         g[k]:= Copy(chaine,k-1,1);
      g[length(chaine)+2]:='+';
 end;
       
procedure nombreetsigne ( g : Green ;chaine : string; var nombre : Integer; var signe : string; var pos : Integer);

var sub : String;

begin
   signe := g[pos];
   sub :='';
   pos := pos +1;
    while ( (g[pos]<>'+') and (g[pos]<>'-') and (pos <= length(chaine)+2)) do
     begin
     sub := sub+g[pos];
     pos := pos+1;
     end;
   nombre := StrtoInt(sub);
end;

function calculerresultat( chaine : string; g : Green ) : Integer;

var  pos , nombre , transit , a: Integer;
     signe : String;

begin
  transit := 0;
  pos := 1;
  a := length(chaine)+2;
   repeat
      begin
      nombreetsigne(g,chaine,nombre,signe,pos);
      if (signe ='+') then
        transit := transit + nombre;
      if ( signe ='-') then
        transit := transit - nombre;
      end;
   until ( pos = a );
  calculerresultat := transit; 
end;


var chaine : String;
       g : Green;
   
begin
    write('entrez votre calcul :');
    readln(chaine);
    classifier(chaine,g);
    writeln(calculerresultat(chaine,g));
end.

The issue was with the array , if i didn't put a + or a - in the end the pos variable will make an overflow in the array ( as it will go to infinite )
that's just it . I'm only asked to handle the + and - operators.

Thanks et Merci a lot guys!

sam707

  • Guest
Re: [Programming ] String to Numbers
« Reply #10 on: May 02, 2018, 12:34:59 am »
de rien, but there are ways to shorten your code ;)

henry01

  • Newbie
  • Posts: 1
Re: [Programming ] String to Numbers
« Reply #11 on: May 05, 2018, 08:18:38 am »
Can you write out an algorithm that completes the task (don't use actual pascal, just describe the steps)?



« Last Edit: May 05, 2018, 01:14:28 pm by theo »

 

TinyPortal © 2005-2018