c - print multiple lines by getchar and putchar -
im beginner learning c programming language , using microsoft visual c++ write , test code.
below program in c text(section 1.5.1) copy input output through putchar() , getchar():
#include <stdio.h> int main(void) { int c; while ((c = getchar()) != eof) putchar(c); return 0;}
the program print characters entered keyboard every time pressing enter.as result,i can enter 1 line before printing. can't find way enter multi-line text keyboard before printing.
is there way , how let program input , output multi-line text keyboard?
sorry if basic , ignorant question.
appreciate attention , in advance.
some clever use of pointer arithmetic want:
#include <stdio.h> /* printf , fgets */ #include <string.h> /* strcpy , strlen */ #define size 255 /* using size nicer magic numbers */ int main() { char input_buffer[size]; /* take user input */ char output_buffer[size * 4]; /* storing multiple lines let's make big enough */ int offset = 0; /* storing input @ different offsets in output buffer */ /* null error checking, if user enters new line, input terminated */ while(fgets(input_buffer, size, stdin) != null && input_buffer[0] != '\n') { strcpy(output_buffer + offset, input_buffer); /* copy input @ offset output */ offset += strlen(input_buffer); /* advance offset length of string */ } printf("%s", output_buffer); /* print our input */ return 0; }
and how use it:
$ ./a.out adas asdasdsa adsa adas asdasdsa adsa
everything parroted :)
i've used fgets, strcpy , strlen. useful functions (and fgets
recommended way take user input).
Comments
Post a Comment