这个C程序编译成功,没有错误:
int main(){
char file1[100];
int count=0;
char c,ch,ck;
FILE *fptr;
printf("Enter the file namen");
scanf("%s", file1);
fptr=fopen(file1, "r");
printf("Enter the character to be countedn");
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;
}
但是在执行时终止,有什么问题请帮助
scanf(" %c",c);
应该是
scanf(" %c",&c);
^ // Notice the ampersand &.
// It is used to get the address which scanf() needs
注意:使用main()
的标准定义
int main(void) //if no command line arguments.
这真的是个问题吗?当开始学习C/C++时,很常见的情况是应用程序完成,所有东西都关闭了,看起来像是错误或失败。。。
原因是控制台应用程序在finisher从其主方法返回后,相关的控制台窗口会自动关闭。这种行为与你的应用程序做什么或不做什么无关,也与应用程序是否正常工作无关。
致";正确的";这个简单的方法是在主方法中的return语句之前添加一个暂停
示例:
....
system("pause");
return 0;
}
将scanf(" %c",c);
更改为scanf(" %c",&c);
并检查fopen的返回值。
fptr=fopen(file1,"r");
if(fptr==NULL) {
printf("failed to open file");
return 1;
}