Reputation: 15
So I try to take a user input of unknown max length from the command line. The program to be able 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 come up with is the following
int main (int argc, char* argv[]){
...
char str1[];
str1 = argv[1];
printf("your...);
...
}
Upvotes: 0
Views: 1122
Reputation: 1922
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;
}
Upvotes: 0
Reputation: 311010
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...);
Upvotes: 2