簡體   English   中英

如何讀取和輸出帶有空格和換行符的輸入

[英]How to read & output an input with spaces and newlines

我正在嘗試在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;
}

使用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的結尾。 我們已經擁有的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM