473,789 Members | 2,893 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
28 5801
ka*****@hotmail .com wrote:
What is the safest way to make an argv[] comparison? The code below
works.
If you use a language with pattern matching and type inference, like OCaml
or F#, then you can just write:

let () = match Sys.argv with
| [|_; test|] when test = "NKDT" ->
printf "\nComparis on is true. Have program do something.\n"
| _ ->
printf "\nComparis on is false. Have program do something else.\n"

The catchall pattern handles everything else safely and simply.

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 22 '07 #21
On 22 Maj, 22:11, Jon Harrop <j...@ffconsult ancy.comwrote:
kafe...@hotmail .com wrote:
What is the safest way to make an argv[] comparison? The code below
works.
[snipped off-topic content]
My advice to you, Jon, is to get a life and refrain from spamming
comp.lang.c++ with off-topic content.

/Peter

May 23 '07 #22
On Tue, 22 May 2007 18:39:43 +0200, Alf P. Steinbach wrote:
* Lionel B:
>>
Beside the point... the fact remains that (as far as we can know) the
"false" branch in the OP's code may be perfectly "unexceptional" . In
fact his/her action for the "false" branch was "Have program do
something else". That doesn't (to me) say "throw exception".

I'm not sure that the effect of the OP's code was intentional,and the
question was how to deal with argv, not how to replicate the effect of
the original code (still I posted such replication else-thread).
To be clear: your code throws when no args are supplied. Surely it is
very common indeed for a program to be validly runable with or without
args - and which will do different things accordingly. Again, I've no
reason to believe the OP either did or didn't intend this and I've no
inclination to second-guess them.
Anyway, it's silly and just plain argumentative to object to getting too
generally useful code.
That clearly wasn't my objection; this was (snipped quote restored):
>Sure, it's a fine idiom if deployed as the OP intended, which I'm not
convinced it was.
Anyway, this is all pretty trivial.

--
Lionel B
May 23 '07 #23
On May 22, 1:57 pm, Gianni Mariani <gi3nos...@mari ani.wswrote:
dave_mikes...@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 upa
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 isa
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.
I think part of the point of Alf's code is that significant
parts of it will eventually end up in a library. For a quicky,
just using something like:

std::vector< std::string args( argv + 1, argv + argc ) ;

is probably sufficient. But real programs have a tendancy to
grow, to acquire options, etc. And it's a lot easier to adopt
Alf's solution to these evolutions than something as primitive
as the above.

--
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 23 '07 #24
* James Kanze:
On May 22, 1:57 pm, Gianni Mariani <gi3nos...@mari ani.wswrote:
>dave_mikes...@ fastmail.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.

I think part of the point of Alf's code is that significant
parts of it will eventually end up in a library. For a quicky,
just using something like:

std::vector< std::string args( argv + 1, argv + argc ) ;

is probably sufficient. But real programs have a tendancy to
grow, to acquire options, etc. And it's a lot easier to adopt
Alf's solution to these evolutions than something as primitive
as the above.
Well yes, right on. If I weren't so lazy I'd add it as a project
template in Visual Studio, or have it as a file I could copy. But I
just type it in manucally whenever I need a small tool for something
(perhaps I'm not lazy enough -- this bears thinking about!). Thought
I should share it, and I couldn't imagine that it would generate any
debate. And as mentioned, I think similar code is given in Accelerated
C++, presumably for the same reason: a simple, reusable skeleton for a
small toy program that needs to handle main arguments.

--
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 23 '07 #25

"Alf P. Steinbach" <al***@start.no wrote in message
news:5b******** *****@mid.indiv idual.net...
Well yes, right on. If I weren't so lazy I'd add it as a project template
in Visual Studio, or have it as a file I could copy. But I just type it
in manucally whenever I need a small tool for something (perhaps I'm not
lazy enough -- this bears thinking about!). Thought I should share it,
and I couldn't imagine that it would generate any debate. And as
mentioned, I think similar code is given in Accelerated C++, presumably
for the same reason: a simple, reusable skeleton for a small toy program
that needs to handle main arguments.
Just a question about your code (which I appreciated as a good example).

Why did you use:

(1)
arguments.size( ) 1
|| throwX( "usage: myprog ARG1" );

and not a plain if as in

(2)
if (aruments.size( ) <= 1) {
throwX( "usage: myprog ARG1" );
}

I've never seen this use, but of course I can understand it (even if I
haven't found it very readable at first sight).
Is (1) written that way because you wanted the condition (arguments.size () >
1) to have the form of a precondition?

--
Marco
May 23 '07 #26
* *PaN!*:
"Alf P. Steinbach" <al***@start.no wrote in message
news:5b******** *****@mid.indiv idual.net...
>Well yes, right on. If I weren't so lazy I'd add it as a project template
in Visual Studio, or have it as a file I could copy. But I just type it
in manucally whenever I need a small tool for something (perhaps I'm not
lazy enough -- this bears thinking about!). Thought I should share it,
and I couldn't imagine that it would generate any debate. And as
mentioned, I think similar code is given in Accelerated C++, presumably
for the same reason: a simple, reusable skeleton for a small toy program
that needs to handle main arguments.

Just a question about your code (which I appreciated as a good example).

Why did you use:

(1)
arguments.size( ) 1
|| throwX( "usage: myprog ARG1" );

and not a plain if as in

(2)
if (aruments.size( ) <= 1) {
throwX( "usage: myprog ARG1" );
}

I've never seen this use, but of course I can understand it (even if I
haven't found it very readable at first sight).
Is (1) written that way because you wanted the condition (arguments.size () >
1) to have the form of a precondition?
Yes, and it's shorter, and it's a very common convention in languages
like Perl (except instead of throwX it's usually "die"). But it's a bit
unconventional. So I would not use it in code that had to maintained by
others not familiar with the idiom.

--
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 23 '07 #27
Alf P. Steinbach wrote:
* *PaN!*:
>"Alf P. Steinbach" <al***@start.no wrote in message
news:5b******* ******@mid.indi vidual.net...
>>Well yes, right on. If I weren't so lazy I'd add it as a project
template in Visual Studio, or have it as a file I could copy. But I
just type it in manucally whenever I need a small tool for something
(perhaps I'm not lazy enough -- this bears thinking about!).
Thought I should share it, and I couldn't imagine that it would
generate any debate. And as mentioned, I think similar code is given
in Accelerated C++, presumably for the same reason: a simple,
reusable skeleton for a small toy program that needs to handle main
arguments.

Just a question about your code (which I appreciated as a good example).

Why did you use:

(1)
arguments.size( ) 1
|| throwX( "usage: myprog ARG1" );

and not a plain if as in

(2)
if (aruments.size( ) <= 1) {
throwX( "usage: myprog ARG1" );
}

I've never seen this use, but of course I can understand it (even if I
haven't found it very readable at first sight).
Is (1) written that way because you wanted the condition
(arguments.siz e() 1) to have the form of a precondition?

Yes, and it's shorter, and it's a very common convention in languages
like Perl (except instead of throwX it's usually "die"). But it's a bit
unconventional. So I would not use it in code that had to maintained by
others not familiar with the idiom.
I have to admit that I don't like it that much in C++. I think the if
statement is much more readable. In perl, the readability is
non-existent anyway :) Probably the statement

do_something or die "with an error";

is one of the most readable :)

Regards,

Zeppe
May 23 '07 #28

"Alf P. Steinbach" <al***@start.no wrote in message
news:5b******** *****@mid.indiv idual.net...

[... preconditions with "cond || throw"...]
I would not use it in code that had to maintained by others not familiar
with the idiom.
Indeed, that was exactly my problem here =)
I was thinking about switching from the actual macro-based approach in a
specific project with other 3 developers, who have a not-too-deep knowledge
of C++.
It's probably a bad idea =)

Thank you,
Marco
May 24 '07 #29

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
5930
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
12616
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
8257
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
3981
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
2203
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
9801
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
7188
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
9665
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...
0
10199
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9020
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
6768
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
5417
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3697
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
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.