getchar() and reading line by line

限于喜欢 提交于 2019-12-06 11:08:44

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!