Jozef Tománek Jozef Tománek - 1 month ago 17
C Question

Int in argv[] breaks and just prints the int

So I know this is basics but I have no clue where to find the right answers. the thing is I need to run a program with argument -s followed by a number telling it how many chars from input to skip, say we do (I run it in bash):

echo "hue" |./prog -s 2


which should then only print the
e
but instead the shell gives me


2someone@somewhere:


I am stuck for hours at this point not being able to figure it out, please, help.

int main(int argc, char *argv[]) {
char s;
char input[8196];
int i = 0;
/* above initialized are variables needed for the root of the program to work */
int s_num = 0; /* "-s" or skip */
int cnt_1; /* lvl1 counter */
/* Getting input */
while ((s = getchar()) != EOF) {
input[i] = s;
printf("%d\n", i);
i++;
}

/* If calling w/o arguments, the only thing that works */
if (argc == 1) {
//do stuff
}

/* Argument Check */
if (argc > 1) {
printf("1\n");
for (cnt_1 = 0; cnt_1 < argc; cnt_1++) {
printf("2\n");

if (strcmp(argv[cnt_1], "-s") == 1) {
printf("3.1\n");
int pom = cnt_1 + 1;
int bqs = 0;
for (int i = 0; argv[pom][i] != '\0'; ++i) {
bqs *= 10; bqs += argv[pom][i] - '0';
}
s_num = bqs;
}
...

Answer

The first argument, i.e. argv[0] contains the name of the executable. So start your search for arguments at the second element of the array argv[1] and go from there.

for (cnt_1 = 1; cnt_1 < argc; cnt_1++)
//           ^  change 0 to 1 here

if, as you say in the comments, you are not allowed to use <string.h>, then perhaps you can perform a char by char comparison of each string contained in the array of strings of argv[] as you go through your loop:

...
if((argv[cnt_1][0] == '-') && (argv[cnt_1][1] == 's'))//argument "-s" found, handle it
{
    ... 
Comments