Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

c - getchar() and reading line by line

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
",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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...