-3

So, I have been working on this simple block of code. I would like it to print, when I type in "./a.out -n"

However, that is not working. I have been on stackoverflow trying to work on this, but no such luck. Any help would be appreciated.

#include <stdio.h>
#include <stdlib.h>
void parse_cmdline(int argc, char *argv);
int main (int argc, char *argv[]) {
  parse_cmdline(argc, argv);
}

void parse_cmdline(int argc, char *argv)
{
   int x,i,m,n = 0;
  if (*(++argv) == 'n'){ 
      x = 1;
      printf("Output array: "); /* not being displayed*/
      }
}

2 Answers2

0

Just write

  if (**++argv == 'n'){ 

And the function should be declared like

void parse_cmdline(int argc, char **argv);

Otherwise you should specify what parameter you are going tp pass to the function. For example

parse_cmdline(argc, argv[1]);

You can check what parameters are passed to the program the following way

int main (int argc, char *argv[]) {
    for ( int i = 0; i < argc; i++ ) puts( argv[i] );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I tried this, but I still am not receiving the output. All I need to type in command prompt "./a.out -n" Am I writing it wrong? – King Kong Nov 13 '16 at 20:41
0

Try:

#include <stdio.h>
#include <stdlib.h>

void parse_cmdline(int argc, char *argv[]);

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

  parse_cmdline(argc, argv);
}

void parse_cmdline(int argc, char *argv[])
{
   int x,i,m,n = 0;
  if (*(argv[1]) == '-' && *(++argv[1]) == 'n'){ 
      x = 1;
      printf("Output array: "); /* not being displayed*/
      }
}

And run it with ./a.out -n. So, I have examined 0th and 1th character of the argv value on the position one ("./a.out" is located on position 0, and "-n" on position 1). Is that what you wanted?

Also, you cannot ignore warnings:

1.c: In function ‘main’:
1.c:5:23: warning: passing argument 2 of ‘parse_cmdline’ from incompatible pointer type [-Wincompatible-pointer-types]
   parse_cmdline(argc, argv);
                       ^
1.c:3:6: note: expected ‘char *’ but argument is of type ‘char **’
 void parse_cmdline(int argc, char *argv);

If you write parse_cmdline(argc, argv); then parse_cmdline should be void parse_cmdline(int argc, char *argv[]);

concrete_rose
  • 198
  • 3
  • 15