Search code examples
cinputoutputgetcharputchar

print multiple lines by getchar and putchar


Im a beginner learning The C Programming language and using Microsoft visual C++ to write and test code.

Below program in C from text(section 1.5.1) copy its input to its output through putchar() and getchar():

#include <stdio.h>
int main(void)
{   int c;
    while ((c = getchar()) != EOF)
         putchar(c);
    return 0;}

The program print characters entered by keyboard every time pressing ENTER.As a result,I can only enter one line before printing. I can't find a way to enter multi-line text by keyboard before printing.

Is there any way and how to let this program input and output multi-line text from keyboard?

Sorry if this is a basic and ignorant question.

Appreciate your attention and thanks in advance.


Solution

  • Some clever use of pointer arithmetic to do what you want:

    #include <stdio.h>  /* this is for printf and fgets */
    #include <string.h> /* this is for strcpy and strlen */
    #define SIZE 255 /* using something like SIZE is nicer than just magic numbers */
    
    int main()
    {
        char input_buffer[SIZE];        /* this will take user input */
        char output_buffer[SIZE * 4];   /* as we will be storing multiple lines let's make this big enough */
    
        int offset = 0; /* we will be storing the input at different offsets in the output buffer */
    
        /* NULL is for error checking, if user enters only a new line, input is terminated */
        while(fgets(input_buffer, SIZE, stdin) != NULL && input_buffer[0] != '\n') 
        {
            strcpy(output_buffer + offset, input_buffer); /* copy input at offset into output */
            offset += strlen(input_buffer);               /* advance the offset by the length of the string */
        }
    
        printf("%s", output_buffer); /* print our input */
    
        return 0;
    }
    

    And this is how I use it:

    $ ./a.out 
    adas
    asdasdsa
    adsa
    
    adas
    asdasdsa
    adsa
    

    Everything is parroted back :)

    I've used fgets, strcpy and strlen. Do look those up as they are very useful functions (and fgets is the recommended way to take user input).