-1

So, I am trying to use argc and argv in Caesars cipher in order to execute the program with just [./ key ;string] (e.g. ./ 13 Caesar). I have tried in lots of ways, although I must admit I am really lost here. I was thinking I should just use main(void) and ask the input with fgets, but I still have some curiosity in: How could I make it work with “int main(int argc, char *argv[])?”. Any clues you can give me?

Thank you for your help. Here is the code with the current outputs:

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




 int main(int argc, char *argv[])
 {
    int key;
    int result;
    char str[60];
    int k = 0;



    printf("argc =%d\n", argc);
    printf("argv =%d\n", argv);
    printf("key =%d\n", key);



 if (argc != 2)
    {
        printf("You didn't enter a key.\n");
        return 1;
    }

 else
    {
        int k = key % 26;
        printf("k =%d\n", k);

        if (k == 0)
        {
            printf("Invalid key.\n");
            return 1;
        }
    }
 }  

Output:

$ ./ceasar 13
argc =2
argv =-13216
key =0
k =0
Invalid key.

Edit: Tentative Answer

 int main(int argc, char* argv[])
{
    int i;
    int key = atoi(argv[1]);
    int result;
    char str[60];

for (i = 0; i < argc; i++)
{
    printf("argv[%d] = %s\n", i, argv[i]);
}

 if (argc != 2)
    {
        printf("You didn't enter a key.\n");
        return 1;
    }
 else
    {

        if (key == 0)
        {
            printf("Invalid key.\n");
            return 1;
        }
    }
}

1 Answers1

1

Printing argv with the "%d" specifier is undefined behavior, read printf()'s manual and use "%p".

On the other hand, if you want to print the string you should access the appropriate element with array notation. For example

printf("First Argument: %s\n", argv[1]);

this applies to all arguments, noting that argv[0] is the name of the executable as invoked in the command line.

You should also be careful before accessing argv[1] to check that argc > 2, and always check the current argument + !.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • I was able to solve a bit of it! I simply had to declare “int key = atoi(argv[1]);” at the beginning. Thank you for your help! – Deiscar PF Nov 24 '16 at 23:33