【发布时间】:2021-03-28 04:46:26
【问题描述】:
这个C程序编译成功,没有错误:
int main(){
char file1[100];
int count=0;
char c,ch,ck;
FILE *fptr;
printf("Enter the file name\n");
scanf("%s", file1);
fptr=fopen(file1, "r");
printf("Enter the character to be counted\n");
scanf(" %c", c); //segmentation fault thrown here
ck = c;
if((int)c>=65 &&(int)c<=90)
c = (int)c+32;
while((ch = getc(fptr))){
if((int)ch>=65 && (int)ch<=90)
ch = (int)ch+32;
if(ch == EOF)
break;
else if(ch == c)
count+=1;
}
printf("File '%s' has %d instances of letter '%c'.",file1,count,ck);
fclose(fptr);
return 0;
}
但在执行时终止,请问是什么问题
【问题讨论】:
-
您总有一天会发现 (a) 留意提升的编译器警告,以及 (b) 检查 IO 操作的结果而不是假设它们有效,这两种技能都值得细细开发。
-
在
return 0;之前使用getch(); -
我尝试了相同的程序并且它工作正常。您确定要输入的文件路径吗?尝试@karthick 代码来检查它是否打开文件。在返回 1 之前使用
getch();;在那个代码中。