简体   繁体   中英

How to read & output an input with spaces and newlines

I am attempting to scanf a multiline input in C and output it. However, I'm having trouble handling spaces and newline characters. If the input is:

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

I want to output all three lines. But my output ends up being just:

Hello.

Here's my code:

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

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

Its much easier to use fgets() :

#include <stdio.h>

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

An empty line (first character is newline) ends input.


If you have to read all input first before printing the result, things get a little bit more complicated:

#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
}

*) and it is also more efficient since strcat() would have to find the end of text before appending the new string. Information we already have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM