Search code examples
cencryptioncastingdo-whilecaesar-cipher

Integer receives wrong value from stringv[]


Caesar Cypher - Basic encryption.

I'd ask for your help to understand why variable k receives negative value even if second command line (argv[1]) equals 3, for example.

int main (int argc, string argv[])
{
    string text;
    int k = 0;

    do 
    {
        printf("Type in a plain text:\n");
        text = GetString();

//k receives wrong value
        k = (int) argv[1]; 

// Sanity check
        printf ("argv[1] is %s and k is %d\n", argv[1], k);
    }
    while (k < 0);

Solution

  • What you need to do here is a conversion rather than a type-cast, hence type-casting to int won't help, you need to convert the char * to int using a library function, like the commonly used int atoi (const char *str), which is defined in the header file stdlib.h. Don't forget to #include it. !

    However, I would suggest using strtol, because of it's robust error reporting. It specifies the return value on overflow (returns LONG_MIN in case of an underflow and LONG_MAX in case of an overflow) and also allows the user to set the base to be followed during the conversion.