strtol

Section: C Library Functions (3)
Updated: 2026-02-08
Index JM Home Page roff page
 

名前

strtol, strtoll, strtoq - 文字列を long int に変換する  

ライブラリ

標準 C ライブラリ (libc,~-lc)  

書式

#include <stdlib.h>

long strtol(const char *restrict nptr,
            char **_Nullable restrict endptr, int base);
long long strtoll(const char *restrict nptr,
            char **_Nullable restrict endptr, int base);

glibc 向けの機能検査マクロの要件 (feature_test_macros(7) 参照):

strtoll():

    _ISOC99_SOURCE
        || /* glibc <= 2.19: */ _SVID_SOURCE || _BSD_SOURCE
 

説明

strtol() 関数は、 nptr の文字列の最初の部分を、 base を基数として long int に変換する。 この base は 2 から 36 までの値 あるいは特別な意味を持つ値 0 でなければならない。

The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional '+' or '-' sign. If base is zero or 16, the string may then include a "0x" or "0X" prefix, and the number will be read in base 16; if base is zero or 2, the string may then include a "0b" or "0B" prefix, and the number will be read in base 2; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).

The remainder of the string is converted to a long value in the obvious manner, stopping at the first character which is not a valid digit in the given base. (In bases above 10, the letter 'A' in either uppercase or lowercase represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.)

If endptr is not NULL, and the base is supported, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not '\0' but **endptr is '\0' on return, the entire string is valid.

strtoll() 関数は strtol() と同様だが、 long long 型の値を返す。  

返り値

アンダーフローもオーバーフローも起きなかった場合、 strtol() 関数は 変換された値を返す。オーバーフローした場合には LONG_MAX が返り、 アンダーフローした場合には LONG_MIN が返る。オーバーフロー、 アンダーフローのいずれの場合にも 大域変数 errno には ERANGE が設定される。 strtoll() も同様であるが、 LONG_MIN と LONG_MAX の代わりに LLONG_MIN と LLONG_MAX が返される。  

エラー

This function does not modify errno on success.
EINVAL
(C99 にはない) 指定された base がサポートされていない値である。
ERANGE
結果の値が範囲外である。

実装によっては、変換が行われなかった場合 (数字がなく、0 を返した場合)、 errno に EINVAL が設定される場合がある。  

属性

この節で使用されている用語の説明については、 attributes(7) を参照。
インターフェース属性値
strtol(), strtoll(), strtoq() Thread safetyMT-Safe locale
 

バージョン

POSIX.1 では、 "C" と "POSIX" 以外のロケールでは、これらの関数は、他の実装時に定義される数字を示す文字列を受け付けるとされている。

BSD には、

quad_t strtoq(const char *nptr, char **endptr, int base);

という完全に同様の定義を持つ関数がある。 使用中のアーキテクチャーのワード長次第であるが、この関数は strtoll() か strtol() と等価となることもある。  

標準規格

C23, POSIX.1-2024.  

歴史

strtol()
POSIX.1-2001, C89, SVr4, 4.3BSD.
strtoll()
POSIX.1-2001, C99.
"0b", "0B"
C23. glibc 2.38. (Not in POSIX.)
 

警告

 

Range checks

Since strtol() can legitimately return 0, LONG_MAX, or LONG_MIN (LLONG_MAX or LLONG_MIN for strtoll()) on both success and failure, the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno == ERANGE after the call.

errno = 0;
n = strtol(s, &end, base);
if (end == s)
        goto no_number;
if ((errno == ERANGE && n == _Minof(long)) || n < min)
        goto too_low;
if ((errno == ERANGE && n == _Maxof(long)) || n > max)
        goto too_high;
 

base

If the base needs to be tested, it should be tested in a call where the string is known to succeed. Otherwise, it's impossible to portably differentiate the errors.

errno = 0;
strtol("0", NULL, base);
if (errno == EINVAL)
    goto unsupported_base;
 

バグ

 

White space

These functions silently accept leading white space. To reject white space, call isspace(3) before strtol().  

例

以下のプログラムは strtol() の使用例である。 最初のコマンドライン引数には strtol() が数字として解釈する文字列を指定する。 (省略可能な) 二番目の引数には 変換に使用される基数を指定する (この引数は atoi(3) を使って数値に変換される。 atoi(3) は strtol() よりも簡単なインターフェースを持つ関数で、 その中ではエラーチェックは行われない)。 このプログラムの実行例をいくつか以下に示す:

$ ./a.out 123
strtol() returned 123
$ ./a.out '    123'
strtol() returned 123
$ ./a.out 123abc
strtol() returned 123
Further characters after number: "abc"
$ ./a.out 123abc 55
strtol: Invalid argument
$ ./a.out ''
No digits were found
$ ./a.out 4000000000
strtol: Numerical result out of range
 

プログラムのソース

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    int base;
    char *endptr, *str;
    long val;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    str = argv[1];
    base = (argc > 2) ? atoi(argv[2]) : 0;

    errno = 0;    /* To distinguish success/failure after call */
    strtol("0", NULL, base);
    if (errno == EINVAL) {
        perror("strtol");
        exit(EXIT_FAILURE);
    }

    errno = 0;    /* To distinguish success/failure after call */
    val = strtol(str, &endptr, base);

    /* Check for various possible errors.  */

    if (errno == ERANGE) {
        perror("strtol");
        exit(EXIT_FAILURE);
    }

    if (endptr == str) {
        fprintf(stderr, "No digits were found\n");
        exit(EXIT_FAILURE);
    }

    /* If we got here, strtol() successfully parsed a number.  */

    printf("strtol() returned %ld\n", val);

    if (*endptr != '\0')        /* Not necessarily an error.  */
        printf("Further characters after number: \"%s\"\n", endptr);

    exit(EXIT_SUCCESS);
}
 

関連項目

atof(3), atoi(3), atol(3), strtod(3), strtoimax(3), strtoul(3)


 

Index

名前
ライブラリ
書式
説明
返り値
エラー
属性
バージョン
標準規格
歴史
警告
Range checks
base
バグ
White space
例
プログラムのソース
関連項目

This document was created by man2html, using the manual pages.