3

For one of my exercises, we're required to read line by line and outputting using ONLY getchar and printf. I'm following K&R and one of the examples shows using getchar and putchar. From what I read, getchar() reads one char at a time until EOF. What I want to do is to read one char at a time until end of line but store whatever is written into char variable. So if input Hello, World!, it will store it all in a variable as well. I've tried to use strstr and strcat but with no sucess.

while ((c = getchar()) != EOF)
{   
    printf ("%c", c);
}
return 0;
Zack Bloom
  • 8,309
  • 2
  • 20
  • 27
franchise842
  • 35
  • 1
  • 1
  • 4
  • Can't you store all the characters in one line and just read each character of the array until you have a null character? – stanigator Feb 05 '11 at 19:15
  • @stanigator: Then you have to deal with what happens when you run out of memory. A better approach would be to forget about lines and read some moderate-size fixed `N` chars at a time. – R.. GitHub STOP HELPING ICE Feb 05 '11 at 20:29

1 Answers1

4

You will need more than one char to store a line. Use e.g. an array of chars, like so:

#define MAX_LINE 256
char line[MAX_LINE];
int c, line_length = 0;

//loop until getchar() returns eof
//check that we don't exceed the line array , - 1 to make room
//for the nul terminator
while ((c = getchar()) != EOF && line_length < MAX_LINE - 1) { 

  line[line_length] = c;
  line_length++;
  //the above 2 lines could be combined more idiomatically as:
  // line[line_length++] = c;
} 
 //terminate the array, so it can be used as a string
line[line_length] = 0;
printf("%s\n",line);
return 0;

With this, you can't read lines longer than a fixed size (255 in this case). K&R will teach you dynamically allocated memory later on that you could use to read arbitarly long lines.

nos
  • 223,662
  • 58
  • 417
  • 506
  • can you explain what " line[line_length] = 0; " does and why you have to terminate the array? – franchise842 Feb 06 '11 at 02:09
  • @franchise842 It simply sets the char after the last read input to 0. In C, strings are terminated by the char 0 - they're nul terminated(a byte with the value 0, not the character '0') - otherwise it is not a string This is how string functions know when the string ends, e.g. printf will stop when it encounters the 0 char. strlen() will count the number of characters up till the first 0 char. – nos Feb 07 '11 at 23:08