0

I want to compare the different elements of a command-line argument. It would be entered all together resulting in the string being found at argv[1]. However, I am not sure how to compare the elements and individual characters as I am looking for repetitions.

If I compared [2] to [3] in the string, there would be nothing there as only 1 string is entered in the command line argument and I need to compare the characters found within that string argv[1]. I am unable to include spaces so I wouldn't be able to compare argv[2] to argv[1].

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    The first argument is `argv[1]` and its individual characters are `argv[1][0]`, `argv[1][1]`, `argv[1][2]`, `argv[1][3]`, etc. Is that what you're asking? – John Kugelman Jan 18 '21 at 09:46
  • 1
    Though it is possible to parse the arguments yourself, you are better off using a library for this, e.g. argp http://nongnu.askapache.com/argpbook/step-by-step-into-argp.pdf Relevant : https://stackoverflow.com/questions/9642732/parsing-command-line-arguments-in-c – Willem Hendriks Jan 18 '21 at 09:58
  • Welcome to StackOverflow! Please take the [tour] and read "[ask]". Then come back and [edit] your question. Please provide a [example], show us your input, what you get, and what you expect instead. – the busybee Jan 18 '21 at 13:48

1 Answers1

0

Read Modern C and see this C reference.

If you code for Linux, read also documentation of GNU libc, in particular the section on parsing program arguments.

You could also use strcmp(3) to compare your program argument to some fixed constant string.

The program arguments are given to your main function, traditionally defined as int main(int argc, char**argv). They are always strings (of different addresses), and on POSIX you are practically certain that argc>0, argv[0] is a non-empty string (somehow the name of the program), all argv[i] with i >= 0 and i < argc are non-null, and argv[argc] is NULL.

You could code inside your main something like

 if (argc>1 && !strcmp(argv[1], "foo")) {
    /// handle `foo` as first program argument
 }

I would recommend to study for inspiration the source code of GNU findutils or of GNU make.

I don't recommend modifying program arguments with e.g. some code like strcpy(argv[1], "bar"). It is not portable, perhaps forbidden, and certainly unreadable and brittle.

If you are on Linux, see also proc(5) about /proc/self/cmdline

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547