【问题标题】:Get rid of segmentation fault by using scanf with or without & sign通过使用带有或不带有 & 符号的 scanf 来消除分段错误
【发布时间】:2023-04-09 18:25:02
【问题描述】:

在这段代码中,我面临 3 个问题。如何摆脱它们?

  • 问题 1:使用不带 & 符号的 scanf

如果我在没有& 的情况下使用scanf("%s", to_find); 并将to_find 变量设置为50 像这样to_find[50] 那么if 语句不起作用并给我一个像这样的消息exited, segmentation fault

  • 问题 2:将 scanf 与 & 符号一起使用

如果我使用 scanf("%s", &to_find);& 并设置 to_find 变量等于 50 像这样 to_find[50] 然后 scanf 显示这样的消息 warning: format specifies type 'char *' but the argument has type 'char (*)[50]' 并且 if 语句也不起作用,给我这样的消息exited, segmentation fault

  • 问题 #3:使用 fgets

如果我使用 fgets(to_find, 50, stdin); 并设置 to_find 变量等于 50 像这样 to_find[50] 然后 if 语句不起作用给我这样的消息 @987654333 @

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

int main(){
  FILE * fr = fopen("file.csv", "r");
  char save[500], line[200],  to_find[50];
  int oneByOne = 0;

  printf("Enter the ID card number: ");
  scanf("%s", to_find);
  // fgets(to_find, 50, stdin);

  if(isdigit(to_find) && strlen(to_find) ==  13){
    while(fgets(line, 200, fr)){
      char *word = strtok(line, "\n");
      strcpy(save, line);

      if (strstr(save, to_find)){
        char *wordone = strtok(save, ",");
        while (wordone != NULL){
          printf("Here are your details:  %s\n", wordone);
          wordone = strtok(NULL, ",");
        }
      }
    }
    fclose(fr);
  }
  else {    printf("enter correclty");    }
return 0;
}

【问题讨论】:

  • isdigit() 的参数必须是单个 char,而不是字符串。
  • 问题是你误用了isdigit(),而不是scanf()fgets()
  • 您应该收到有关该调用的警告或错误。
  • @KenY-N 不,我无法解释。
  • @Barmar 但是,我们不知道哪个if 崩溃了——也许是strstr() 调用?

标签: c scanf fgets


【解决方案1】:

scanf("%s", to_find) 是读取字符串的正确方法。当用作函数参数时,数组会自动转换为指向第一个元素的指针,因此您无需使用&amp;

您的if 语句不起作用,因为isdigit() 的参数必须是单个char,它不能作用于字符串的所有字符。如果要测试字符串是否完全是数字,可以编写如下函数:

int all_digits(char *s) {
    for (; *s != 0; s++) {
        if (!isdigit(*s)) {
            return 0;
        }
    }
    return 1;
}

那么你就可以使用这个功能了:

if (strlen(to_find) == 13 && all_digits(to_find)) {
    ...
}

我怀疑您实际上在if (isdigit(to_find) &amp;&amp; strlen(to_find) == 13) 语句中遇到了分段错误。取消引用无效指针时会发生分段错误,但 isdigit() 不会取消引用任何指针。如果输入的单词超过 49 个字符,strlen(to_find) 可能会出错,因为scanf() 会溢出变量。

您应该使用调试器来确定错误发生的准确位置。

【讨论】:

  • 我的猜测是 fopen 只是返回 NULL,因为该文件不存在,因为默认目录不是 OP 认为的那个。
  • 很有可能。
  • @BilalKhan 我已经测试了我的代码。它工作正常,如果输入不是数字或不是 13 个字符,您应该只转到print correctly 消息。
  • @BilalKhan 请显示 .csv 文件的最小示例和触发问题的精确输入。 Edit你的问题。
  • @Jabberwocky CSV 文件的内容如何相关?如果它转到else 块,它永远不会尝试读取文件。
猜你喜欢
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
  • 2011-07-18
  • 2014-11-13
相关资源
最近更新 更多