vendredi 23 juillet 2021

Segmentation fault error if argc takes only one argument. This does'nt happen when the IF is before WHILE

Check if the user provides no command-line arguments, or more, it prints Usage: ./caesar key. If the command-line argument is one then it checks if all the characters in the string are digits. If I enter ./caesar in the command line, I get a segmentation fault error. This doesn't happen when the IF is before WHILE. I am not sure as to why this error occurs. Really appreciate any help!

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

   int main(int argc, char*argv[])
   {
    string str = argv[1];
    
  //check if argv[1] are all digits
    while(argc == 2)
    {
      for(int i = 0; i< strlen(str); i++)
       {
          if(!isdigit(str[i]))
          {
             printf("Usage: ./caesar key \n");
             break;
          }
       }
        break;
    }
    
   // check if argument count is not 2
   if(argc != 2)
    {
       printf("Usage: ./caesar key \n");
    }
   
   return 0;

   }

Aucun commentaire:

Enregistrer un commentaire