【发布时间】: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()调用?