在调用 atoi() 之前如何检查以确保您有一个整数? [英] How to check to ensure you have an integer before calling atoi()?

查看:16
本文介绍了在调用 atoi() 之前如何检查以确保您有一个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将一个整数作为命令行参数,但是如果用户传递一个非整数字符串,这将导致堆栈溢出.确保 atoi() 成功的标准方法是什么?

I wish to take an integer as a command line argument, but if the user passes a non-integer string, this will cause a stack overflow. What is the standard way to ensure atoi() will be successful?

推荐答案

您可以使用:

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

然后检查是否*endptr != nptr.这意味着字符串至少以整数开头.您还可以检查 *endptr 是否指向终止零,这意味着整个字符串已成功解析.

Then check if *endptr != nptr. This means that the string at least begins with the integer. You can also check that *endptr points to terminating zero, which means that the whole string was successfully parsed.

这篇关于在调用 atoi() 之前如何检查以确保您有一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆