【问题标题】:How to read & output an input with spaces and newlines如何读取和输出带有空格和换行符的输入
【发布时间】:2018-11-08 19:07:57
【问题描述】:

我正在尝试扫描 C 中的多行输入并将其输出。但是,我在处理空格和换行符时遇到了麻烦。如果输入是:

Hello.
My name is John.
Pleased to meet you!

我想输出所有三行。但我的输出最终只是:

Hello.

这是我的代码:

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

int main() 
{
    char s[100];
    scanf("%[^\n]%*c", &s);
    printf(s);
    return 0;
}

【问题讨论】:

标签: c string input scanf


【解决方案1】:

它更容易使用fgets():

#include <stdio.h>

int main(void)
{
    char buffer[1000];
    while (fgets(buffer, sizeof(buffer), stdin) && buffer[0] != '\n') {
        printf("%s", buffer);
    }
}

一个空行(第一个字符是换行符)结束输入。


如果您必须在打印结果之前先读取所有输入,事情会变得有点复杂:

#include <stddef.h>  // size_t
#include <stdlib.h>  // EXIT_FAILURE, realloc(), free()
#include <stdio.h>   // fgets(), puts()
#include <string.h>  // strlen(), strcpy()

int main(void)
{
    char buffer[1000];
    char *text = NULL;  // pointer to memory that will contain the whole text
    size_t total_length = 0;  // keep track of where to copy our buffer to

    while (fgets(buffer, sizeof(buffer), stdin) && buffer[0] != '\n') {
        size_t length = strlen(buffer);  // remember so we don't have to call
                                         // strlen() twice.
        // (re)allocate memory to copy the buffer to:
        char *new_text = realloc(text, total_length + length + 1); // + 1 for the
        if (!new_text) {  // if (re)allocation failed              terminating '\0'
            free(text);   // clean up our mess
            fputs("Not enough memory :(\n\n", stderr);                   
            return EXIT_FAILURE;
        }
        text = new_text;  // now its safe to discard the old pointer
        strcpy(text + total_length, buffer);  // strcpy instead of strcat so we don't
        total_length += length;               // have to care about uninitialized memory 
    }                                         // on the first pass *)

    puts(text);  // print all of it
    free(text);  // never forget
}

*) 并且它也更有效,因为strcat() 必须在附加新字符串之前找到text 的结尾。我们已经掌握的信息。

【讨论】:

  • 也可以检查 EOF。
  • @FiddlingBits fgets()EOF 上返回NULL
  • 您的第一个 sn-p 代码运行良好。不过,我很欣赏你第二部分的彻底性!
  • @JoaoFodao 好吧,如果你不需要那样做,也许有一天它会帮助别人:)
  • 正是...哎呀,也许有人会是我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2022-11-02
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多