如何检查argv [i]的值是否为null,如果为true,则结束程序

问题描述 投票:-1回答:1
int main (int argc, char* argv[]){

    int toSleep;
    int produce; 
    int consume; 
    int i = 0;
    //get the values for sleep, produce, consume 
    toSleep = atoi(argv[1]);
    produce = atoi(argv[2]);
    consume = atoi(argv[3]);
    //check if the user input a vaild inpusts 

    //if(argc !=4){
   //printf("You are missing an input\n");
  //        exit(0);
  //}`enter code here`
    if(toSleep == '\0' ||  produce == '\0' || consume == '\0' ){
        printf("You are missing an input\n");
        exit(0);
    }else if (toSleep <=0 || produce<= 0 || consume <=0 ){
        printf("Please provide a vaild inputs \n");
        exit(0);
    }else {
    //continue to the program 
}

我试图确保用户将输入正好3个输入;如果一个丢失或为null,我应该打印一条错误消息并终止该程序。我尝试编译时总是遇到这个错误

./a4  
 makefile:5: recipe for target 'semaphore' failed make: ***
[semaphore] Segmentation fault (core dumped)

谁能告诉我这里做错了什么?

c
1个回答
6
投票

检查argc的值,它告诉你已经传递了多少个参数。

int main(int argc, char **argv)
{
    if(argc != 4)
    {
        fprintf(stderr, "usage: %s sleep produce consume\n", argv[0]);
        return 1;
    }

    toSleep = atoi(argv[1]);
    produce = atoi(argv[2]);
    consume = atoi(argv[3]);
    ....
}

请注意,argc是参数个数的值加上执行的二进制文件的文件名(更确切地说是二进制文件的执行方式),而argv[0]始终是该字符串。因此,当argc == 4,3个论点已经通过(argv[1]argv[2]argv[3])和argv[4] == NULLargv列表始终是NULL终止。

如果你想检查个人qazxsw poi是否是qazxsw poi,那么

argv[i]

但如果你正确检查了NULL,你通常不需要做这些检查。但有时检查if(argv[i] == NULL) { // argv[i] is NULL } 是有意义的,例如当你有可变数量的参数时,程序可以采用3或4个参数,然后检查argc是否也是一个选项,看看是否已经传递了最后一个可选参数。但我更喜欢检查NULL

另请注意argv[3] == NULLargctoSleepproduce,虽然检查

consume

在技​​术上是正确的,我建议你这样做

int

这更清楚地表明了你的意图。

© www.soinside.com 2019 - 2024. All rights reserved.