C语言 如何从文本文件中打印带有空格的句子?

pprl5pva  于 2023-01-12  发布在  其他
关注(0)|答案(1)|浏览(93)

我试图从input.txt文件中复制文本,但是程序认为空格是新行。我该怎么做?
我的输入. txt (试用版)

1. hero
2. angelic
3. hello world
4. demons

我的来源. c

int main(void) {

FILE* fread = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");

if (fread == NULL) {
    printf("One file wouldn't open!\n");
    return -1;
}

    //this pastes the text from input.txt into the command-line
char line[1000] = "";
while (fscanf(fread, "%s", line) == 1) {
    printf("%s\n", line);
}

fclose(fread);
fclose(fwrite);

输出

1.
hero
2.
angelic
3.
hello
world
4.
demons
s8vozzvw

s8vozzvw1#

这是你要做的。已经有函数实现来帮助你做这件事。

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

int main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
    if (fp == NULL){
        printf("One file wouldn't open!\n");
        exit(EXIT_FAILURE);
    }

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        printf("%s", line);
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}

相关问题