确定 C 字符串是否是 C 中的有效 int [英] Determine if a C string is a valid int in C

查看:22
本文介绍了确定 C 字符串是否是 C 中的有效 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个 C 字符串是否是一个有效的整数.

I need to check if a C string is a valid integer.

我都试过了

int num=atoi(str);

int res=sscanf(str, "%d", &num);

但是在两行中发送字符串"8 -9 10" 返回的只是8,没有说明这个字符串的无效性.

But sending the string "8 -9 10" in both of the lines returned simply 8, without indicating the invalidity of this string.

有人可以提出替代方案吗?

Can anyone suggest an alternative?

推荐答案

看看 strtol(),它可以通过指针返回告诉你字符串的无效部分.

Have a look at strtol(), it can tell you about invalid parts of the string by pointer return.

注意那些热情洋溢的示例代码.有关全面的错误处理,请参阅手册页.

And beware of enthusiastic example code.. see the man page for comprehensive error-handling.

这篇关于确定 C 字符串是否是 C 中的有效 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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