Reputation: 47
I'm playing around with command line arguments and I've been trying to have a comparison between the argument number and the input. So if someone input 1 then the output would be "The difficulty level is 1".
#include <iostream>
#include <cstring>
using namespace std;
int main(ijnt argc, char* argv[])
{
int a;
if (argc[1] == '1')
{
cout << "The difficulty level is " << argv[1] << endl;
return 1;
}
}
I made the comparing 1 a char but I get the error "ISO C++ forbids comparison between pointer and integer [-fpermissive]" and says that the error is
if (argv[1] == '1')
How do I get the 1 that is getting compared to, to be accepted as a char?
Upvotes: 1
Views: 565
Reputation: 48615
The command line arguments are character arrays and so you need to use something like std::strcmp()
to compare them like this:
int main(int argc, char* argv[])
{
// check argument exists ...
if(!std::strcmp(argv[1], "1")) // 0 when equal
{
// they are the same here
}
// ...
}
It may be simpler to just create a `std::string out of the arg
if(std::string(argv[1]) == "1")
{
// they are the same here
}
In all cases make sure you check whether or not the argument is present:
int main(int argc, char* argv[])
{
if(!argv[1]) // argument not present (null terminated array)
{
std::cerr << "Expected an argument." << std::endl;
return EXIT_FAILURE;
}
// process arg here
// ...
}
Upvotes: 0
Reputation: 21576
argv
is an array of character array...
So, use strcmp
and compare, or better still, convert it to an std::string
and compare... But also make sure that argc
is greater than 1. Example:
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char* argv[])
{
int a;
if (argc > 1 && strcmp(argv[1], "1") == 0)
{
cout << "The difficulty level is " << argv[1] << endl;
return 1;
}
}
or
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
int a;
if (argc > 1 && string(argv[1]) == "1")
{
cout << "The difficulty level is " << argv[1] << endl;
return 1;
}
}
Upvotes: 1