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. You use strcmp in string.h
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.