将字符串转换为int(但仅当确实是int时) [英] Convert a string to int (But only if really is an int)

查看:77
本文介绍了将字符串转换为int(但仅当确实是int时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大学里,我被问到程序是否检测到从命令行参数输入的字符串是否为整数(./Program 3.7).现在,我想知道如何检测到这一点.因此atoi会检测到例如a的输入无效,但是例如3.6的输入应该是无效的,但是atoi会将其转换为整数.

In college I was asked if our program detects if the string enter from command line arguments is a integer which it did not(./Program 3.7). Now I am wondering how I can detect this. So input as for example a is invalid which atoi detects, but input like for example 3.6 should be invalid but atoi will convert this to an integer.

#include <stdio.h>

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

但是,仅当argv [1]确实是整数时,才应打印偏离路线的行列.希望我的问题清楚.非常感谢.

But offcourse okay should only be printed if argv[1] is really an integer. Hope my question is clear. Many thanks.

推荐答案

看看

如果endptr不为NULL,则strtol()将第一个无效字符的地址存储在* endptr中.但是,如果根本没有数字,则strtol()将str的原始值存储在* endptr中. (因此,如果* str返回时不是\0' but **endptr is \ 0',则整个字符串都是有效的.)

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 \0' but **endptr is \0' on return, the entire string was valid.)

#include <stdio.h>
#include <stdlib.h>

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

这篇关于将字符串转换为int(但仅当确实是int时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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