* (e-mail address removed):
* (e-mail address removed):
What is the safest way to make an argv[] comparison? The code below
works.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string test;
if(argc>1)
test = argv[1];
if(test=="NKDT")
cout << "\nComparison is true. Have program do something.\n";
else
cout << "\nComparison is false. Have program do something else.\n";
return 0;
}
Do the following:
<snip>
What was wrong with the OP's solution, which appeared to be much more
concise?
Probably directly wrong: always indicating success for the program
execution. Also probably directly wrong: doesn't handle exceptions.
However, one might design a program so that no exception should ever
propagate up to main and if it does one wants termination for ease of
debugging, not a report and failure indication. So it depends on design
and methodology and toolchain and to some extent personal preference.
But I don't think the lack of exception handling here was intentional.
Ungood: the main code has direct access to argc and argv, when the aim
is to handle them in "the safest way" (giving access is unsafe). Also
ungood in general: "using namespace std:;". Also ungood: not using
curly braces for nested statements (just about any style guideline will
tell you to use them, always, in order to support maintenance).
Appearance of conciseness: all of the OP's code is program-specific,
whereas the code I listed is mostly boilerplate, a kind of
micro-framework for this particular kind of small student program or
professional's check-it-out program or single-use personal tool program.
For consisness one could write e.g. (doing the /same/ as the OP's code)
#include <string>
#include <iostream>
int main( int n, char* a[] )
{
using namespace std;
n > 1 && std::string( a[1] ) == "NKDT"
? cout << "\nComparison is true. Something.\n"
: cout << "\nComparison is false. Something else.\n";
}
getting rid of the local variable 'test' and also the 'return 0' which
is implied (it's the default) in 'main', and just to make it extra
concise I also removed that darned 'else' which otherwise would use up a
very expensive line, and the keyword 'if' which is so much to read. I
simply don't understand why so many programmers think conciseness is a
goal. They just end up not understanding their own code.