【问题标题】:Help comparing an argv string帮助比较一个 argv 字符串
【发布时间】:2021-06-01 04:18:10
【问题描述】:

我有:

int main(int argc, char **argv) {
   if (argc != 2) {
      printf("Mode of Use: ./copy ex1\n");
      return -1;
   }

   formatDisk(argv);
}

void formatDisk(char **argv) {
   if (argv[1].equals("ex1")) {
       printf("I will format now \n");
   }
}

如何在 C 语言中检查 argv 是否等于 "ex1"? 是否已经有一个功能? 谢谢

【问题讨论】:

    标签: c argv


    【解决方案1】:
    #include <string.h>
    if(!strcmp(argv[1], "ex1")) {
        ...
    }
    

    【讨论】:

    • 您应该同时检查 null 还是先确保该索引存在?
    • argc 给出了 argv 中参数的数量,因此 (if argc != 2) 的检查确保 argv[1] 存在。
    • 另外值得注意的是 strncmp() 函数,它比较字符串的前 'n' 个字节。 (manpagez.com/man/3/strncmp)
    【解决方案2】:

    只是给出一个使用字符串和动态分配新字符串的例子。当你不知道 argv[?]

    的大小时可能很有用
    // Make the string with the value you want compared
    char testString[] = "-command";
    
    // Make a char pointer, use new to allocate the memory 
    //  the size is determined by string length of argv[1]
    char * strToTest = new char[ strlen( argv[1] ) ];
    
    // Now we can copy the contents of argv[1] into strToTest as they are equal size
    strcpy( strToTest, argv[1] );
    
    // Now strcmp returns True if the two strings match
    if (strcmp( testString, strToTest ) {
    //do somthing here ...
    }
    

    【讨论】:

    • 为什么我们需要 argv[1] 的副本? strcmp 接受 const char *
    • @Raja;副本不是必需的。这纯粹是为了在答案中塞入额外的字符串函数示例。因为如果您正在查找此问题,您可能也希望看到这些:) ... 如答案的前两句话所述。
    • new 不是很 c-ish :> (回答 12 岁的帖子)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    相关资源
    最近更新 更多