Home > Software engineering >  C user dynamic input with argv
C user dynamic input with argv

Time:12-20

So I try to take an user input of unknown max length from the command line. The programm to be aple to do something like that needs to take a dynamic input of a string (char array maybe?). The outcome should be something like

./a.out st1 your str is ...

the only code I was able to comee up with is the following

int main (int argc, char* argv[]){
...
char str1[];
str1 = argv[1];
printf("your...);
...
}

CodePudding user response:

This declaration of a block scope array with an empty number of elements:

char str1[];

is incorrect. Moreover arrays do not have the assignment operator:

str1 = argv[1];

You could declare a pointer:

char *str1;
str1 = argv[1];
printf("your...);

CodePudding user response:

C will terminate argv with a null pointer, and argv is modifiable, so it's actually very easy to implement shift like in bash scripts. Your basis could look like the following.

#include <stdio.h>

int main(int argc, char *argv[]) {
    char *arg;
    if(!argc || !argv[0]) return 0; /* Defensive */
    while(arg = *(  argv))
        printf("do something with %s\n", arg);
    return 0;
}
  • Related