Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c - 如何在C中将字符串转换为整数?(How to convert a string to integer in C?)

I am trying to find out if there is an alternative way of converting string to integer in C.

(我正在尝试找出是否有在C中将字符串转换为整数的替代方法。)

I regularly pattern the following in my code.

(我定期在代码中设置以下内容。)

char s[] = "45";

int num = atoi(s);

So, is there a better way or another way?

(那么,有没有更好的方法或另一种方法?)

  ask by user618677 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is strtol which is better IMO.

(有strtol是更好IMO。)

Also I have taken a liking in strtonum , so use it if you have it (but remember it's not portable):

(我也很喜欢strtonum ,所以如果有的话就用它(但要记住它不是便携式的):)

long long
     strtonum(const char *nptr, long long minval, long long maxval,
     const char **errstr);

EDIT (编辑)

You might also be interested in strtoumax and strtoimax which are standard functions in C99.

(您可能也对strtoumaxstrtoimax感兴趣,它们是C99中的标准功能。)

For example you could say:

(例如,您可以说:)

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
    /* Could not convert. */

Anyway, stay away from atoi :

(无论如何,请远离atoi :)

The call atoi(str) shall be equivalent to:

(调用atoi(str)应等效于:)

 (int) strtol(str, (char **)NULL, 10) 

except that the handling of errors may differ.

(除了错误处理可能有所不同。)

If the value cannot be represented, the behavior is undefined .

(如果无法表示该值,则行为是undefined 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...