C 程序在读取第一个输入后暂停

问题描述 投票:0回答:1

我正在开发一个 C 程序,旨在删除 .txt 文件中文本之间的空白行。该程序询问用户源文件和目标文件的名称。但是,我遇到一个问题,程序在收到源文件的名称后似乎暂停或挂起。只有在用户第二次按回车键后,它才会继续询问目标文件名。我尝试过使用 scanf 和 fgets,还尝试刷新标准输入缓冲区,但问题仍然存在。我在最近 3-4 个实验中使用了获取文件名的确切代码,所以我不知道出了什么问题。程序在到达第一个 fopen 时结束。此时 if 语句运行并且为 True.. 因此源文件名在某种程度上被误解了。

这是代码:

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

int main() {
    FILE *source, *destination;
    char source_file_name[256], destination_file_name[] = "output.txt", buffer[1024];

    // Prompts user for file name to search, reads the name into our buffer, and stores the file name. Will also clear the buffer.
    printf("Enter the source file name: "); 
    fgets(buffer, sizeof(buffer), stdin);
    sscanf(buffer, "%s", source_file_name);

    // Prompts user for file name to use for the copy.
    printf("\nWhat would you like to name the duplicate file? (default name: output.txt): ");
    fgets(buffer, sizeof(buffer), stdin);
    if(strlen(buffer) > 1) { // If a name is entered, it is used. If not, the default is used.
        sscanf(buffer, "%s", destination_file_name);
    }
    source = fopen(source_file_name, "r");
    if(!source) {
        perror("The source file was not found.");
        return 1;
    }

    destination = fopen(destination_file_name, "w");
    if(!destination) 
    {
        perror("Could not create the destination file.");
        fclose(source); // Close the source file before exiting.
        return 1;
    }

    while (fgets(buffer, sizeof(buffer), source)) {
        char *p = buffer;
        int blank_space = 1;
        while(*p != '\0') {
            if (!isspace((unsigned char) *p)) {
                blank_space = 0;
                break;
            }
            p++;
        }
        if(!blank_space) {
            fputs(buffer, destination);
        }
    }

    fclose(source);
    fclose(destination);

    return 0;   
}

观察到的行为:

输入源文件名并按回车键后,程序不会立即提示输入目标文件名。好像要等我再次按回车键。

尝试修复:

  • 在 scanf 的格式字符串中使用空格来忽略前导空格。
  • 用 fgets 替换 scanf 并手动删除换行符。
  • 第一次 scanf 后显式刷新标准输入缓冲区。

操作系统:Windows 11

IDE:VS Code

c buffer newline flush
1个回答
0
投票

我在代码中看到的唯一问题是@JonathanLeffler 之前提到的缓冲区溢出。

如果任何行超过 1023 字节,那么您可能会删除很长行中间的空格。您至少应该记录下来,或者如果您的假设无效,最好生成一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.