如何从txt文件中打印带有空格的句子?

huangapple go评论49阅读模式
英文:

how to print sentences with spaces from a txt?

问题

我试图从 input.txt 文件复制文本,但程序将空格视为换行符。我应该如何处理这个问题?

我的 input.txt (试验)

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

我的 source.c

int main(void) {

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

    if (fread == NULL) {
        printf("一个文件无法打开!\n");
        return -1;
    }

    // 这将从 input.txt 中粘贴文本到命令行
    char line[1000] = "";
    while (fscanf(fread, "%s", line) == 1) {
        printf("%s\n", line);
    }

    fclose(fread);
    fclose(fwrite);
}

输出

hero
2.
angelic
3.
hello
world
4.
demons

英文:

I'm trying to copy text from a input.txt but programs thinks spaces are new lines. How should I go about this?

my input.txt (trial)

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

my source.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);

output

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

答案1

得分: 1

这是您要做的事情。已经有一个实现这个功能的函数可以帮助您完成这个任务。

#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("无法打开文件!\n");
        exit(EXIT_FAILURE);
    }

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("读取到长度为 %zu 的行:\n", read);
        printf("%s", line);
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}
英文:

Here is what you do. There is already function implemented to help you in doing this.

#define _GNU_SOURCE
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

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

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

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

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

huangapple
  • 本文由 发表于 2023年1月9日 17:34:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定