c ++检查命令行参数

0 c++ command-line exception

我需要在命令行参数中检查两个单独的文件名.

./a.out hello.txt hello2.txt
Run Code Online (Sandbox Code Playgroud)

当两个文件名相同时,以下代码不会产生错误.

  #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';
     }
  }
Run Code Online (Sandbox Code Playgroud)

Hal*_*acı 5

argv是一个字符串,因此您无法比较"=="运算符.你在string.h中使用strcmp

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