473,778 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

argv[] comparison

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 << "\nComparis on is true. Have program do something.\n";
else
cout << "\nComparis on is false. Have program do something else.\n";

return 0;
}

May 21 '07 #1
28 5799
* ka*****@hotmail .com:
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 << "\nComparis on is true. Have program do something.\n";
else
cout << "\nComparis on is false. Have program do something else.\n";

return 0;
}
Do the following:

#include <iostream>

#include <cstddef>
#include <string>
#include <vector>
#include <stdexcept>

typedef std::vector<std ::stringStringV ector;

bool throwX( char const s[] ) { throw std::runtime_er ror( 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;
}
}
--
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?
May 21 '07 #2
On May 21, 2:39 pm, "Alf P. Steinbach" <a...@start.now rote:
* kafe...@hotmail .com:


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 << "\nComparis on is true. Have program do something.\n";
else
cout << "\nComparis on 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?
May 21 '07 #3
* da***********@f astmail.fm:
On May 21, 2:39 pm, "Alf P. Steinbach" <a...@start.now rote:
>* kafe...@hotmail .com:
>>>
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 << "\nComparis on is true. Have program do something.\n";
else
cout << "\nComparis on 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 << "\nComparis on is true. Something.\n"
: cout << "\nComparis on 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.

--
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?
May 21 '07 #4
On May 21, 8:31 pm, "kafe...@hotmai l.com" <kafe...@hotmai l.comwrote:
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 << "\nComparis on is true. Have program do something.\n";
else
cout << "\nComparis on is false. Have program do somethingelse.\ n";
return 0;
}
It depends on context. For simply "quicky" programs, I just do
it as I did in C, something like:

if ( argc 1 && strcmp( argc[ 1 ], "NKDT" ) == 0 ) {
// ...
}

As soon as the program ceases to be trivial, however, I'll use a
library based solution which strips out the options, and exposes
the remaining arguments as a std::vector<std ::string>, or
something similar. Thus, my own code would be something like:

int
main( int argc, char** argv )
{
Gabi::CommandLi ne& args( Gabi::CommandLi ne::instance() ) ;
args.parse( argc, argv ) ;
if ( args.size() 1 && args[ i ] == "NKDT" ) {
// ...
} else {
// ...
}
return Gabi::ProgramSt atus::returnCod e() ;
}

Such binary selections are more often handled by means of
options, however:

int
main( int argc, char** argv )
{
Gabi::BooleanOp tion isNKDT( "NKDT" ) ;
Gabi::CommandLi ne& args( Gabi::CommandLi ne::instance() ) ;
args.parse( argc, argv ) ;
if ( isNKDT ) {
// ...
} else {
// ...
}
return Gabi::ProgramSt atus::returnCod e() ;
}

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 22 '07 #5
ka*****@hotmail .com wrote:
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 << "\nComparis on is true. Have program do something.\n";
else
cout << "\nComparis on is false. Have program do something else.\n";

return 0;
}
Use a command line parser like the one in CommmonC++ :-)

#include <cc++/common.h>

ost::CommandOpt ionArg NKDT_Option(
"NKDT", "p", "--NKDT is for super stuff"
);

ost::CommandOpt ionNoArg helparg(
"help", "?", "Print help usage"
);

int main( int argc, char ** argv )
{

CommandOptionPa rse * args = ost::makeComman dOptionParse(
argc, argv,
"This command is so special !"
);

if ( helparg.numSet ) {
cerr << args->printUsage() ;
::exit(0);
}

if ( NKDT_Option.num Set )
{
cout << "\nHave program do something.\n";
return result;
} else {
cout << "\nHave program do something else.\n";
return result;
}
}

.....

The nice thing about this is that anywhere in your code, you can add
ost::CommandOpt ionXXX options and they're picked up automatically. So
main does not get complicated with every possible option. The command
option parser automatically pulls together all the parameters to create
a usage.

It's a little outdated in that it was written before std::string was
working properly on most compilers so it use C style stings everywhere.
May 22 '07 #6
On May 21, 4:28 pm, "Alf P. Steinbach" <a...@start.now rote:
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.
The OP's example was nothing like that. Conciseness does not
necessarily lead to obfuscation, your strawman notwithstanding .
I simply don't understand why so many programmers think conciseness is a
goal.
Nor I why so many tend to overcomplicate simple solutions to simple
problems.
They just end up not understanding their own code.
Same thing happens with over-engineered code.

May 22 '07 #7
* da***********@f astmail.fm:
On May 21, 4:28 pm, "Alf P. Steinbach" <a...@start.now rote:
>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.

The OP's example was nothing like that. Conciseness does not
necessarily lead to obfuscation, your strawman notwithstanding .
>I simply don't understand why so many programmers think conciseness is a
goal.

Nor I why so many tend to overcomplicate simple solutions to simple
problems.
It is a "standard" solution. I think you'll find it somewhere at the
beginning of Accelerated C++. Although I don't have that book.

If you have questions about it I'll be happy to answer them.

--
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?
May 22 '07 #8
On Mon, 21 May 2007 20:39:14 +0200, Alf P. Steinbach wrote:
* ka*****@hotmail .com:
>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 << "\nComparis on is true. Have program do something.
\n";
> else
cout << "\nComparis on is false. Have program do something
else.\n";
>>
return 0;
}

Do the following:
[snip]

You appear to assume that an exception should be thrown if the command
line does not have a particular form. I see no such requirement expressed
by the OP who does not, in fact, suggest that the "false" comparison is
in any way "exceptiona l".

--
Lionel B
May 22 '07 #9
da***********@f astmail.fm wrote:
On May 21, 4:28 pm, "Alf P. Steinbach" <a...@start.now rote:
>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.

The OP's example was nothing like that. Conciseness does not
necessarily lead to obfuscation, your strawman notwithstanding .
>I simply don't understand why so many programmers think conciseness is a
goal.

Nor I why so many tend to overcomplicate simple solutions to simple
problems.
>They just end up not understanding their own code.

Same thing happens with over-engineered code.
std::vector is part of the standard.
std::string is part of the standard.

What about these is complex ?

There exists a minimum complexity. employing char * is usually bad news
and is prone to far more subtle complexity that is exemplified by the
OP's question.

Alf's code does more like what you would expect.

May 22 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2626
by: Robin Sanderson | last post by:
Sorry in advance if this is a stupid question - I am new to C++. In the process of converting program to be run from the command line into a function to be run from another program I noticed behaviour that I do not understand. Consider the example programs below: Program 1 below is a simple program that merely outputs the command line arguments. This compiles and runs fine with Microsoft Visual C++ 6.0 and g++ 3.3.1.
9
5929
by: mahurshi | last post by:
i have a quick question i am putting a debug flag in my program (i really dont need this feature, but i figured it might be useful when i get into trouble) so i want to check if argv is the letter "d" this is what i have so far if (argv) { write_read_input_file(filename); }
28
12606
by: Charles Sullivan | last post by:
I'm working on a program which has a "tree" of command line arguments, i.e., myprogram level1 ]] such that there can be more than one level2 argument for each level1 argument and more than one level3 argument for each level2 argument, etc. Suppose I code it similar to this fragment: int main( int argc, char *argv ) {
13
8255
by: James | last post by:
consider : int main (int argc, char * argv ) { } In exec (2) ; Whose arguments which are passed to main. What is the maximum size of the string. argv = "hello........." ;
5
3980
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
22
2200
by: Joe Smith | last post by:
It is nothing short of embarrassing to feel the need to ask for help on this. I can't see how I would make the main control for this. What I want is a for loop and a test condition. And while I know, from things I pondered 2 decades ago, that a fella can write code without a goto, I'm stuck. /* sieve1.c */ #define whatever 20 #define N whatever
4
9800
by: interec | last post by:
Hi Folks, I am writing a c++ program on redhat linux using main(int argc, wchar_t *argv). $LANG on console is set to "en_US.UTF-8". g++ compiler version is 3.4.6. Q1. what is the encoding of data that I get in argv ? Q2. what is encoding of string constants defined in programs (for example L"--count") ?
11
6063
by: vicky | last post by:
hi all, please tell me with example, how the *argv point to the the no of strings.
4
7187
by: Romulo Carneiro | last post by:
Hi, I'm programming in Windows XP and i'm trying to get all arguments of some application, but i only have gotten five argv. When i put more then five(5), it didn't display. =>Input Command Line: Argumentos.exe MyName Arg_1 Arg_2 Arg_3 Arg_3 Arg_4 Arg_5 Arg_6 =>output of my program: Size of Argc:8 Size of Argv: 4
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10061
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8954
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6722
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5368
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.