为什么我的程序在执行scanf()之前突然终止?

时间:2019-06-13 13:00:54

标签: c scanf terminate

我正在尝试编写代码来替换文本文件中的一行。它可以成功编译,但是一旦尝试扫描要替换的行号,它就会无处终止。

我真的不知道我在做什么错。我也尝试过使用fgets(),但仍然无法正常工作。

#include <stdio.h>
#include <stdlib.h>

#define MAXNAME 30
#define MAXLINE 256

int main(){
    char fileName[MAXNAME];
    FILE *originalFileCheck;

    printf("Input the name of the file to be opened: ");
    scanf("%s", fileName);
    originalFileCheck = fopen(fileName, "r");

    if(originalFileCheck == NULL){
        printf("The file %s was not opened successfully. The program will now terminate.\n", fileName);
        exit(1);
    }
    else{
        FILE *tempFileWrite;
        char tempName[MAXNAME] = "temp.txt";
        tempFileWrite = fopen(tempName, "w");

        char newLine[MAXLINE];
        int lineNum;

        printf("Input the content of the new line: ");
        scanf("%s", newLine);
        printf("Input the number of the line you want to replace: ");
        scanf("%d", &lineNum); /* it terminates WITHOUT scanning this int*/

        char str[MAXLINE];
        int counter = 1;
        while(fgets(str, MAXLINE, originalFileCheck) != NULL){
            if(counter != lineNum){
                for(int i = 0; str[i] != '\0' && str[i] != '\n'; i++){
                    fputc(str[i], tempFileWrite);
                }
                fprintf(tempFileWrite, "\n");
            }
            else{
                 fprintf(newLine, "%s\n", tempFileWrite);
                }
            counter++;
        }

        fclose(tempFileWrite);
        fclose(originalFileCheck);
        ...
        return 0;
}

1 个答案:

答案 0 :(得分:0)

以下建议的代码:

  1. 干净地编译
  2. 检查输入错误
  3. 检查输出错误
  4. 执行所需的功能
  5. 在发生错误时正确清理

现在,建议的代码:

div3