0

when i take the command line input (the key) from the user, how do i store it? the argv[1] (this variable will be clear if you read my code )which the user will provide is supposed to be an integer value...INSIDE a character array!

this was what i made

int main(int argc, string argv[])           
{    int key=argv[1];                            /*THIS IS WHERE THE ERROR HAPPENS*/

    if(argc!=2)
    {
        printf("Enter the key as well, in the command line !\n");
        return 1;
    }

    printf("Plaintext: ");

    string ptext=get_string();

    for(int i=0;i<strlen(ptext);i++)
    {
        if(isalpha(ptext[i]))
        {
            if (islower(ptext[i]))          
            {
                ptext[i]=((int)ptext[i]+key)%26+97;
            }

            if(isupper(ptext[i]))
            {
                ptext[i]=((int)ptext[i]+key)%26+65;
            }
        }
    }


    for(int i=0;i<strlen(ptext);i++)
    {
        printf("%c",ptext[i]);
    }


    printf("\n");


    return 0;

}

while the error is-->

caesar.c:8:9: error: incompatible pointer to integer conversion initializing 'int' with an expression of type 'string' (aka 'char *') [-Werror,-Wint-conversion]
    int key=argv[1];

so, if it isn't an integer value, how do i take that?

thanks!

2 Answers 2

0

argv is basically an array of strings. You can use atoi (ASCII to integer) for parsing a string to an integer.

Do not use argv[1] before you ensure that argc is greater than 1, as otherwise the array element might not even exist, and atoi might segfault.

There's no need to int-cast the characters, but don't forget to subtract 'A' before adding the key, and applying %26, and adding 'A' again ('A' is same as 65).

4
  • do you mean i "convert" argv[1] to int even though argv[1] is itself an int? Mar 10, 2017 at 14:29
  • i thought about it for some time, and here's what i think why i need to do what you said-- i am storing two string elements in a string array, argv[].. it doesn't matter if the second array element is a number since that will be a string as well.. now i need to get the integer value of the second element which is in string format, so i have to use atoi function to get that !! Mar 10, 2017 at 14:39
  • please guide me if the thought process is wrong :) Mar 10, 2017 at 14:39
  • Use atoi(argv[1]), but please only after checking argc! atoi parses a string that contains a decimal representation of a number.
    – Blauelf
    Mar 10, 2017 at 15:19
0

argv[] is declared as a string at the top of your code, in int main(int argc, string argv[]). Thus, declaring it simply as an int won't work. Functions like atoi(), which converts a string to an integer, might help!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .