Val

From Free Pascal wiki

Deutsch (de) English (en) русский (ru)
The procedure system.val attempts to convert a string representation of a numeric value into a numeric value variable. It is part of the default run-time library delivered with the FreePascal compiler, but otherwise not standardized.

usage

The formal signature reads:

procedure val(const s: string; var v; var code: word)

S is a string-type expression; it must be a sequence of characters that form a (possibly signed) number or enumerated type value. V is an ordinal or real-type variable. Code is a word integer variable.

If the string s can not be converted to a numeric value, code holds the index of the first character causing troubles; otherwise code is zero, indicating success.

Note-icon.png

Note: In contrast to read, the value of v remains unchanged if no data (i.e. empty string s) is available. No default value is assigned.

The procedure val is so useful, since it does not trigger run-time errors or exceptions. Unlike read the user can be supplied with more useful error messages telling which character is not a numeric symbol. The power of val lies in its capability to also convert enumerated types by their named values.

program valDemo(input, output, stdErr);
type
	decision = (no, yes, maybe);
var
	s: string;
	r: decision;
	c: word;
begin
	writeLn('Are you OK?');
	readLn(s);
	val(s, r, c);
	writeLn('So ', r, '.');
end.

Note, as a general design principle this feature should not be used for user responses like this example shows, since it thwarts internationalization. Localization in general is not possible with val, most notably the decimal separator – in some regions a comma, in others a period – can not be customized; it is always a period, as it is standard in your Pascal source code.

see also