整数を文字列に変換する (Free Pascal)
整数を文字列に変換するコードを書いた。
var
i : integer;
begin
i := 1;
while i < 10 do begin
writeln('no' + i);
i := i + 1;
end;
end.
たいていの言語だと、整数i は自動型変換されて、
no1
no2
…
と出力されるだろうけど、Pascalの場合はエラーになる。
$ fpc mytest.pas
...
mytest.pas(9,22) Error: Incompatible types: got "SmallInt" expected "ShortString"
...
ちゃんと整数を文字列に変換してあげなくてはならないのね。
しかし、どうやって?
調べてみると、次の関数が見つかった。
str(w, s) --- 整数または実数型のwパラメータを文字列s に変換する。
これを使って書いたのが、次のコード。
mytest.pas
program mytest;
var
i : integer;
s : string;
begin
i := 1;
while i < 10 do begin
str(i, s);
writeln('no' + s);
i := i + 1;
end;
end.
実行例
$ fpc mytest.pas
Free Pascal Compiler version 3.2.2+dfsg-9ubuntu1 [2022/04/11] for x86_64
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling mytest.pas
Linking mytest
15 lines compiled, 0.1 sec
$ ./mytest
no1
no2
no3
no4
no5
no6
no7
no8
no9
参考
このpdfの一番最後に書かれてあった。
カテゴリー: memo, Pascal
タグ: str(), 変換, 整数, 整数を文字列に変換, 文字列
カウント: 283
My開発メモ