0

I'm solving the Vigenere Cipher of Pset2, but when I compile the program, it shows an error:

format specifies type 'int' but the argument has type 'unsigned long' [-Werror,-Wformat]

I am not sure what this error message means, I Googled the error message, but I don't quite understand, can anyone tells me what's that about? Thank you.

Below is my code:

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

//Declare variables
string key;
string text;

//check user's input value
int main (int argc, string argv[])
{
    if(argc != 2)
     {
      printf("Please insert ONE key\n");
      return 1;
     }

     for (int i = 0, n = strlen(argv[1]); i < n; i++)
      {
       if(!isalpha(argv[1][i]))
        {
         return 1;
         printf("Please insert an ALPHABETICAL key\n");
        }
      }

    //Get the text
    text = GetString();
    key = argv[1];

    //cipher
    for(int j = 0, l = strlen(text); j < l; j++)
    {
     if(isalpha(text[j]))
      {
       for(int p = 0, m = strlen(key); p < m; p++)
        {
         if(isupper(text[j]))
          {
           printf("%c", ((((text[j] - 65) + key[p]%strlen(key))% 26) + 65));
          }
         else
         printf("%c", ((((text[j] - 97) + key[p]%strlen(key))% 26) + 97));
        }
      }
     else
     printf("%c", text[j]);
    }

    printf("\n");
    return 0;
}
1
printf("%c", ((((text[j] - 65) + key[p]%strlen(key))% 26) + 65));

The problem arises because of how strlen() was used here. strlen() returns a value of type size_t, which is actually an unsigned long. This is implicitly casting the overall result as an unsigned long as well. The compiler looks at this and sees that it's trying to insert it into a %c, and it throws an error.

The bigger problem is that the formula for encoding the letter is incorrect. It is applying the %strlen(key) to the value of the key, not the index. If it were applied to the index instead, the error disappears.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • That was an utterly prompt answer! And it works! Thanks a lot! And I hope I've accepted this answer correctly.
    – Makoto
    Dec 7 '16 at 5:18

You must log in to answer this question.

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