C语言 在 C 中使用 argv?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2300744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:32:25  来源:igfitidea点击:

Using argv in C?

cargv

提问by Joe

For an assignment, I am required to have command line arguments for my C program. I've used argc/argv before (in C++) without trouble, but I'm unsure if C style strings are affecting how this works. Here is the start of my main:

对于作业,我需要为我的 C 程序提供命令行参数。我之前(在 C++ 中)使用过 argc/argv 没有问题,但我不确定 C 风格的字符串是否会影响它的工作方式。这是我的主要内容的开始:

int main(int argc, char *argv[]){

  if(argc>1){
    printf("0 is %s, 1 is %s\n",argv[0],argv[1]);
    if(argv[1]=="-e"){
        // Do some stuff with argv[2]
        system("PAUSE");
    }
    else{
        printf("Error: Incorrect usage - first argument must be -e");
        return 0;
    }
  }

So I am calling my program as "program.exe -e myargstuff" but I am getting the "Error: Incorrect Usage..." output, even though my printf() tells me that argv[1] is "-e". Some help, please? Thanks!

所以我将我的程序称为“program.exe -e myargstuff”,但我得到了“错误:不正确的用法...”输出,即使我的 printf() 告诉我 argv[1] 是“-e”。请帮忙?谢谢!

回答by jgottula

The line

线

if(argv[1]=="-e"){

compares pointers, not strings. Use the strcmpfunction instead:

比较指针,而不是字符串。改用strcmp函数:

if(strcmp(argv[1],"-e")==0){

回答by Dawid

Change:

改变:

if(argv[1]=="-e"){

to

if(strcmp(argv[1], "-e") == 0){

and include string.h.

并包括string.h.

回答by Carl Norum

Check out getopt()and related functions; it'll make your life a lot easier.

签出getopt()及相关功能;它会让你的生活更轻松。

回答by goatlinks

You can't compare c-strings like that. Use strcmp (reference here).

你不能像那样比较 c 字符串。使用 strcmp(参考此处)。

Because c-strings are actually pointers, the == operator compares the address of the first character which will never be equal in this case.

因为 c 字符串实际上是指针,所以 == 运算符比较在这种情况下永远不会相等的第一个字符的地址。

回答by Laurence Gonsalves

You can't use ==to compare strings like that in C. That's just comparing the addresses of argv[1] and your literal, which are pretty much guaranteed to be different.

你不能==用来比较像 C 中那样的字符串。那只是比较 argv[1] 和你的文字的地址,它们几乎可以保证是不同的。

Use strcmpinstead. eg:

使用strcmp来代替。例如:

if (!strcmp("-e", argv[1])) {

回答by zneak

The prototype of the main function says you're dealing with char*pointers. In C, there is no operator overloading; therefore, ==between two char*will test if they point to the same place. This is not the case, and is rarely the case at all. Use the strcmp(the reference for the function is valid even though it points to a C++ site) function from <string.h>:

main 函数的原型表示您正在处理char*指针。在 C 中,没有运算符重载;因此,==两者之间char*将测试它们是否指向同一个地方。事实并非如此,而且这种情况很少发生。使用strcmp(该函数的引用是有效的,即使它指向 C++ 站点)函数来自<string.h>

strcmp(argv[1], "-e") == 0