-3

I need to use the execusion parameters argc and argv and print n time the message. This n number must be higher than 1. So the outup should looke like:

        $ ./hello1 3    
        $ hello1 1!
        $ hello1 2!
        $ hello1 3!

I understand how argc and argv works, more or less, but i don't have any idea of how I can solve this. Any of you know any page where I can find any explanation? My code is and I am aware it is not correct:

#include <stdio.h>

int main(int argc, char*argv[])
{
    if (argc>0)
    for (int i=1; i<=argc; i++){
        printf("Hello1 %d!", i);
    }
    else if (argc==0){
        printf("not correct");
    }
    else{
        printf("number must be greater thant 0");
    }

    return 0;
}
atzru090
  • 1
  • 1

1 Answers1

1

You probably want something like this:

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

int main(int argc, char*argv[])
{
    if (argc > 1)
    {                                 // at least 1 argument provided
      int number = atol(argv[1]);     // convert 1st command line argument to number

      for (int i = 1; i <= number; i++)
      {
        printf("Hello1 %d!\n", i);
      }
    }
    else
        printf("not correct\n");      // no arguments provided

    return 0;
}

Your code was using the number of arguments (argc) instead of the value actually passed on the command line (argv[1], 3 in your example).

Examples of execution:

$ ./Hello1 3
Hello1 1!
Hello1 2!
Hello1 3!

$ ./Hello1 2
Hello1 1!
Hello1 2!
$
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 1
    Good example, a short explanation of what the root problem was (picking argc instead of the program argument stored in argv) would improve learning effects imo – Trickzter Sep 28 '20 at 09:51