简体   繁体   English

如果 argc 只接受一个参数,则出现分段错误。 当 IF 在 WHILE 之前时不会发生这种情况

[英]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.检查用户是否没有提供命令行参数,或者更多,它会打印 Usage: ./caesar key。 If the command-line argument is one then it checks if all the characters in the string are digits.如果命令行参数为 1,则它检查字符串中的所有字符是否都是数字。 If I enter ./caesar in the command line, I get a segmentation fault error.如果我在命令行中输入 ./caesar,则会出现分段错误错误。 This doesn't happen when the IF is before WHILE.当 IF 在 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;

   }

./casear is argv[0] meaning string str = argv[1]; ./casearargv[0]意思是string str = argv[1]; is null resulting in a seg fault.为 null 导致段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM