rezon rezon - 1 month ago 6
C Question

Error when using inputting string containing parenthesis as command line argument

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

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

if (argc < 2) {
printf("Incorrect command line arguments.\n");
return 0;
}
for (int i = 0; i < strlen(argv[1]);i++){
printf("%c",argv[1][i]);
}
printf("\n");
}


I have this simple code, however after compiling this is my output:

./a.out 123
123
./a.out (1+2+3)
bash: syntax error near unexpected token `1+2+3'


What is the reason this is happening, and how can I fix it? it seems like its the parenthesis which is messing this up. Thanks

Answer

The () characters have special meaning to bash. Use quotes to force bash to treat them as ordinary characters:

./a.out '(1+2+3)'
Comments