我需要在命令行参数中检查两个单独的文件名。
./a.out hello.txt hello2.txt
当两个文件名相同时,以下代码不会产生错误。
#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是字符串,因此您无法比较“ ==”运算符。您在string.h中使用strcmp
if (argc != 3 || strcmp(argv[1],argv[2])==0)
{
throw invalid_argument("Error");
}
关于c++ - C++检查命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37559407/