c++ - 在 C++ 中使用 if/then 语句解析 argv[ ] 选项

标签 c++ if-statement argv

根据输入的选项/参数,您将如何使用 argv[] 的 if/then 语句?

例如,a.out -d 1 sample.txta.out -e 1 sample.txt

int main (int argc, char *argv[])
{
  ifstream infile(argv[3]);

  int c;
  int number = 0;
  int count = 0;

  while ( infile.good() ) {

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

                 c = infile.get();

                 number = atoi(argv[2]);  

                  if (number == count)
                 {
                 cout.put(c);
                 count = 0;
                 }

                      else
                        count++;

            }       


           if (argv[1] == "-e")
           { 
              cout << "entered -e" << endl;   //testing code
           }


  }//end while

}//end main

最佳答案

你不能使用相等运算符来比较 C 风格的字符串,你必须使用 std::strcmp :

if (std::strcmp(argv[1], "-d") == 0)

这背后的原因是 == 运算符比较的是指针,而不是它们指向的内容。

关于c++ - 在 C++ 中使用 if/then 语句解析 argv[ ] 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13599915/

相关文章:

shell - Cygwin bash -c 根据命令是否以 c 开头 :/or something else 产生不同的 argc

c++ - 用 SWIG 包装 std::complex<float> 的 4 维 std::vector

c++ - 为什么在 exe 中找到损坏的名称?

c++ - 如何反转位集中的位?

c - 将 argv 给出的内存地址分配给 c 中的指针

C++ 将 argv 读入 unsigned char 固定大小 : Segmentation fault

c++ - 我是否正确计算了我的 FPS?

javascript - 创建对话树时,如何正确使用带 if 语句的提示?

bash - 具有多个条件的 if 语句

c++ - 有没有比使用 "if"更快/更短的方式在 C++ 中进行这些测试?