c - getchar() and reading line by line -


for 1 of exercises, we're required read line line , outputting using getchar , printf. i'm following k&r , 1 of examples shows using getchar , putchar. read, getchar() reads 1 char @ time until eof. want read 1 char @ time until end of line store whatever written char variable. if input hello, world!, store in variable well. i've tried use strstr , strcat no sucess.

while ((c = getchar()) != eof) {        printf ("%c", c); } return 0; 

you need more 1 char store line. use e.g. array of chars, so:

#define max_line 256 char line[max_line]; int line_length = 0;  //loop until getchar() returns eof //check don't exceed line array , - 1 make room //for nul terminator while ((c = getchar()) != eof && line_length < max_line - 1) {     line[line_length] = c;   line_length++;   //the above 2 lines combined more idiomatically as:   // line[line_length++] = c; }   //terminate array, can used string line[line_length] = 0; printf("%s\n",line); return 0; 

with this, can't read lines longer fixed size (255 in case). k&r teach dynamically allocated memory later on use read arbitarly long lines.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -