简体   繁体   English

C ++检查命令行参数

[英]c++ Check command line arguments

I need to check for two separate file names in a command line argument. 我需要在命令行参数中检查两个单独的文件名。

./a.out hello.txt hello2.txt

The following code is not producing an error when the two file names are identical. 当两个文件名相同时,以下代码不会产生错误。

  #include <stdio.h>
  #include <iostream>
  #include <stdexcept>

  using namespace std;

  int main (int argc, char *argv[])
  {
     try
     {
        if (argc != 3 || argv[1] == argv[2])
        {
           throw invalid_argument("Error");
        }
     }
     catch (invalid_argument &ex)
     {
        cout << ex.what() << '\n';
     }
  }

argv is a string so you cannot compare "==" operator. argv是字符串,因此您无法比较“ ==”运算符。 You use strcmp in string.h 您在string.h中使用strcmp

if (argc != 3 || strcmp(argv[1],argv[2])==0)
    {
       throw invalid_argument("Error");
    }

This line 这条线

argv[1] == argv[2]

compares pointers, not the actual string values 比较指针,而不是实际的字符串值

Try 尝试

!strcmp(argv[1] , argv[2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM