【问题标题】:program terminating while executing [closed]程序在执行时终止[关闭]
【发布时间】: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();;在那个代码中。

标签: c file terminate


【解决方案1】:
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.

【讨论】:

  • 是的,先生,我更改了程序仍在终止。 (输入待统计字符后程序终止)
  • @jhansigud, 打印完最后一条语句后退出。
【解决方案2】:

这真的有问题吗?在开始学习 C/C++ 时,应用程序完成并且所有内容都关闭使其看起来像错误或失败是很常见的......

原因是控制台应用程序一旦完成器从它们的 main 方法返回,相关的控制台窗口就会自动关闭。此行为与您的应用执行与否或应用是否运行良好无关。

要“纠正”这个简单的问题,请在 main 方法中的 return 语句之前添加一个暂停

示例:

....
   system("pause");  
   return 0;
}

【讨论】:

  • 还是不行,先生。
  • pause 不可移植。
【解决方案3】:

scanf(" %c",c);更改为scanf(" %c",&amp;c);并检查fopen的返回值。

fptr=fopen(file1,"r");
if(fptr==NULL) {
   printf("failed to open file");
   return 1;
}

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多