加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将字符串转换为int(但仅当真的是int时)

发布时间:2020-12-16 10:39:10 所属栏目:百科 来源:网络整理
导读:在大学里,我被问到我们的程序是否检测到从命令行参数输入的字符串是否是一个它没有的整数(./ Program 3.7).现在我想知道我怎么能发现这个.因此例如a的输入是无效的,其中atoi检测到,但是例如3.6的输入应该是无效的但是atoi将其转换为整数. #include stdio.hin
在大学里,我被问到我们的程序是否检测到从命令行参数输入的字符串是否是一个它没有的整数(./ Program 3.7).现在我想知道我怎么能发现这个.因此例如a的输入是无效的,其中atoi检测到,但是例如3.6的输入应该是无效的但是atoi将其转换为整数.

#include <stdio.h>

int main(int argc,char *argv[]) {
    if (argc > 1) {
        int number = atoi(argv[1]);
        printf("okayn");
    }
}

但是只有当argv [1]真的是一个整数时才应该打印出来.希望我的问题很明确.非常感谢.

解决方法

看看 strtol.

If endptr is not NULL,strtol() stores the address of the first invalid character in *endptr. If there were no digits at all,however,strtol() stores the original value of str in *endptr. (Thus,if *str is not ' but **endptr is′ on return,the entire string was valid.)

#include <stdio.h>

int main(int argc,char *argv[]) {
  if (argc > 1) {
    char* end;
    long number = strtol(argv[1],&end,0);
    if (*end == '')
      printf("okayn");
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读