0

I have this code that's supposed to check if the "key" ie argv(1) but it's not working. "Segmentation fault"

Here it is:

string plain; //this is in advance for my for loop
              //was unable to find a way to actually get the thing to handle a non-numeric key :(

int main(int argc, string argv[])
{
  if (argc == 2 && isdigit(argv[1]))
  {
    plain = get_string("plaintext:");
    printf("ciphertext:");
  }
  else
  {
    printf("Usage : ./caesar key\n");
    return 1;
  }

Thanks for help, if you need any more details please ask!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Ragnaroni
  • 37
  • 5

2 Answers2

3

Let me start by mentioning that all of your problems are caused by CS-50, a horrible, harmful class that will make you a bad C programmer.

In reality the format of argv is char* argv[], an array of character pointers. By doing isdigit(argv[1]) you pass a char* to the function, not a character as it expects. Here a standard C compiler will complain along the lines of "expected character, got pointer" since the code isn't valid.

If the purpose was to check the first digit of the string, you should have done isdigit(argv[1][0]). Also note that isdigit resides in ctype.h so you must include that header. If the purpose was to check if all characters in the string were digits, you will need a loop.

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

argv[1] has the type char * while the function isdigit expects an argument of the type char. So this if statement

if (argc == 2 && isdigit(argv[1]))

is incorrect.

Either you need to write a separate function that checks that each character in the string pointed to by the expression argv[1] represents a digit. Or you could use the standard function strtol and check that the conversion of the string to integer performed by the function was successful.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335