0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C > strtol() > 変換失敗の判断 > res = strtol(src, &endptr, 0); if (src == endptr) {

Last updated at Posted at 2015-11-08

strtol()を使う時、数値かどうかの判断をどうするのか。

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

nptr が指す文字列中に変換不可能な文字があった場合には,その文字列へのポインタを endptr に格納します.

endptrをチェックすればいいのだろうか。

try1

# include <stdio.h>

void funcStrtol(char *src)
{
	int res;
	char *endptr;
    res = strtol(src, &endptr, 0);
    if (strcmp(src, endptr) != 0) {
	    printf("%d %s\n", res, endptr);
    } else {
    	printf("Error %s\n", src);
    }
}

int main(void) {
    int res;
    char *endptr;
    const char *strA = "A";
    const char *str0 = "0";
    const char *str1 = "1";

	funcStrtol(strA);
	funcStrtol(str0);
	funcStrtol(str1);

	return 0;
}
結果
Error A
0 
1 

戻り値
変換が不可能な場合: 0

変換が不可能な場合に0の戻り値となるが、"0"を変換したときとかぶる、というのが始まりの疑問だった。

try2

src と endptrのチェックでもよさそう。

void funcStrtol(char *src)
{
	int res;
	char *endptr;
    res = strtol(src, &endptr, 0);
//    if (strcmp(src, endptr) != 0) {
    if (src != endptr) {
	    printf("%d %s\n", res, endptr);
    } else {
    	printf("Error %s\n", src);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?