简体   繁体   English

使用来自命令行参数的输入将整数与非整数类型进行比较。 C

[英]Compare integer to non integer type using input from command line arguments. C

I am looking to compare a users input to an integer once they enter some type whether that be a string or float etc. into the command line.一旦用户在命令行中输入某种类型(无论是字符串还是浮点数等),我希望将用户输入与整数进行比较。 If the input is not an integer, i want to produce an error message.如果输入不是整数,我想产生一条错误消息。 I have tried using isdigit() and if(atoi(argv[i])>=0) but have had no luck.我曾尝试使用isdigit()if(atoi(argv[i])>=0)但没有运气。 How do i go about doing this?我该怎么做? Thanks in advance.提前致谢。

if( argc != 4 )
{
    printf("invalid.\n");
    error();
}
else if(atoi(argv[1]) >= 1 && atoi(argv[2]) >= 1 && atoi(argv[3]) >= 0){
    N = atoi(argv[1]);
    M = atoi(argv[2]);
    seed = atoi(argv[3]);

    mult(N,M,mat1,mat2,seed);
}
else
{
    printf("invalid argument.\n");
    error();

}

command line input:命令行输入:

$./filename 1 2 e

this still runs my program but i want it to exit when there's a non integer input.这仍然运行我的程序,但我希望它在有非整数输入时退出。

Your program treats the third argument differently from the other two because you have atoi(argv[3]) >= 0 whereas the other two atoi() outputs are tested >= 1 .您的程序将第三个参数与其他两个参数不同,因为您有atoi(argv[3]) >= 0而其他两个atoi()输出经过测试>= 1 A return value of 0 can mean EITHER "I parsed that successfully and got an integer value of 0" OR "I couldn't parse that successfully" so the interpretation is conflated there if you wish to allow value 0 but don't perform additional checks.返回值 0 可能意味着“我成功解析并得到了 0 的整数值”或“我无法成功解析”因此如果您希望允许值 0 但不执行其他解释,则解释会在那里混淆检查。

Note also that ./filename 1x 2 3 is considered "valid" by your program.另请注意,您的程序将./filename 1x 2 3视为“有效”。 You may wish to take additional steps to ensure that the complete argument is a valid integer representation.您可能希望采取额外的步骤来确保完整的参数是一个有效的整数表示。

A better approach to both of these problems would involve switching to strtol or strtoul instead of atoi .解决这两个问题的更好方法是切换到strtolstrtoul而不是atoi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM