Aftershock
Aftershock

Reputation: 5351

string to integer conversion in Pascal, How to do it?

How to convert a number printed in a string into integer?

Thank you.

Upvotes: 6

Views: 47706

Answers (5)

Kai Burghardt
Kai Burghardt

Reputation: 1560

Since ISO standard 10206 “Extended Pascal” the procedure readStr is built‑in into the programming language. It is equivalent in function to read/readLn in conjunction with a text file (except that no text file is needed). That means leading blanks are ignored, followed by one valid integer literal which is terminated by blanks or simply the end of string. Example:

program readStrDemo(output);
    var
        n: integer;
    begin
        readStr('  +1234 Hello world!', n);
        writeLn(n) { prints 1234 }
    end.

In contrast to Borland Pascal’s val procedure you cannot emit a user‑friendly error message, though, specifically which (first) character is causing troubles. Pascal’s built‑in read, readLn and readStr procedures simply fail, the specifics are processor‐dependent. On the other hand, read, readLn and readStr are standardized so there is no vendor lock‑in.

Note, in addition to reading decimal integer literals, read/readLn/readStr can parse any integer literal that is legal in your Pascal source code, including base‑prefixed integer literals such 16#FF (255).

Upvotes: 1

Peternak Kode Channel
Peternak Kode Channel

Reputation: 586

You can use like this,

var

i: integer;
s: string;
begin
str(i, s);
write(i);

Upvotes: 0

The is procedure Val:

procedure Val(S; var V; var Code: Integer);

This procedure operate on decimal and real numbers.

Parmeters:

  • S char sequence; for proper conversion it has to contain ‘+’, ‘-‘, ‘,’, ’.’, ’0’..’9’.
  • V The result of conversion. If result going to be an Integer then S can't contain ‘,’, ’.’.
  • C Return the position of the character from S, that interrupt the conversion.

Use cases:

Var Value :Integer;

Val('1234', Value, Code);  // Value = 1234, Code = 0
Val('1.234', Value, Code); // Value = 0, Code = 2
Val('abcd', Value, Code);  // Value = 0, Code = 1

Upvotes: 11

Mazhar Karimi
Mazhar Karimi

Reputation:

 Textval := '123';
    Val(Textval, Number, Code)  ---> Code = 0, Number = 123

   Textval := '12345x2';
   Val( Textval, Number, Code)  ---> Code = 6,  Number remains unchanged;

Val( TextVal, Number , Code) which converts String to a number. if possible the result of code = 0, elese error indication number.

Upvotes: 1

pyCoder
pyCoder

Reputation: 501

You can use Val function.

Example:

var
   sNum: String;
   iNum: Integer;
   code: Integer;

begin
   s := '101';
   Val(s, iNum, code); 
end.

Upvotes: 0

Related Questions