Reputation: 5351
How to convert a number printed in a string into integer?
Thank you.
Upvotes: 6
Views: 47706
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
Reputation: 586
You can use like this,
var
i: integer;
s: string;
begin
str(i, s);
write(i);
Upvotes: 0
Reputation: 30865
The is procedure Val:
procedure Val(S; var V; var Code: Integer);
This procedure operate on decimal and real numbers.
Parmeters:
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
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
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