1

我是 cpp 的初学者,对以下代码有疑问。通常它应该根据 argv[1] 显示文本,但它不显示任何内容。

我究竟做错了什么?

#include <stdio.h>

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

  if(argv[1] == "a" && argc > 1)  printf("hello world, argc: %d\n", argc);
  else if(argv[1] == "2" && argc > 1) printf("hello everyone, argc: %d\n", argc);

  for(int i=0; i<argc; i++) printf("%s\n", argv[i]);

  return 0;
}
4

2 回答 2

5

Using strcmp, the following code should work:

#include <stdio.h>
#include <string.h>

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

  if(argc > 1 && strcmp(argv[1], "a") == 0) {
      printf("hello world, argc: %d\n", argc);
  } else if(argc > 1 && strcmp(argv[1], "2") == 0)  {
      printf("hello everyone, argc: %d\n", argc);
  }

  for(int i=0; i<argc; i++) printf("%s\n", argv[i]);

  return 0;
}

Since the question is tagged C++, use something like the following to be more C++-like:

#include <iostream>
#include <string>

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

  if(argc > 1) {
      std::string argv1(argv[1]);

      if (argv1 == "a") {
          std::cout << "hello world, argc: " << argc << std::endl;
      } else if (argv1 == "2") {
          std::cout << "hello everyone, argc: " << argc << std::endl;
      }
  }

  for(int i=0; i<argc; i++) {
      std::cout << argv[i] << std::endl;
  }

  return 0;
}
于 2013-06-28T08:47:22.117 回答
3

2 most important issues with you code:

  • You SHALL check number of arguments BEFORE arguments check.
  • Strings are compared using standard library functions like strcmp() or even better strncmp() if you know maximum length.

Here is the C code that works. Hope this help.

#include <stdio.h>
#include <string.h>

int main (int argc, char* argv[])
{
    if ((argc > 1) && ((strcmp(argv[1], "a") == 0)))
    {
        printf("hello world, argc: %d\n", argc);
    }
    else if ((argc > 1) && (strcmp(argv[1], "2") == 0))
    {
        printf("hello everyone, argc: %d\n", argc);
    }

    for (int i = 0; i < argc; i++)
        printf("%s\n", argv[i]);

    return 0;
}

Some details aout string comparison. If you use == operator here (if you have not overloaded it) you just compare object addresses (look carefully, you have char * in both cases). Obviously your string literal and argument buffer have different addresses. You need to compare contents. Actually in C++ you can construct std::string and use comparison operator.

So another, more C++ solution that works based on == operator:

#include <stdio.h>
#include <string>

int main (int argc, char* argv[])
{
    if ((argc > 1) && (std::string(argv[1]) == "a"))
    {
        printf("hello world, argc: %d\n", argc);
    }
    else if ((argc > 1) && (std::string(argv[1]) == "2"))
    {
        printf("hello everyone, argc: %d\n", argc);
    }

    for (int i = 0; i < argc; i++)
        printf("%s\n", argv[i]);

    return 0;
}
于 2013-06-28T08:47:04.073 回答