的getchar()和逐行读取行 [英] getchar() and reading line by line

查看:354
本文介绍了的getchar()和逐行读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关我的运动之一,我们必须逐行读取和仅使用getchar函数和printf输出。我下面的K&安培; R和其中一个例子显示使用的getchar和的putchar。从我读的getchar()读取一次,直到EOF一个字符。我想做的是在同一时间,直到无论是写入字符变线,但店里的末尾改为一个字符。因此,如果输入的Hello,World!将所有存储在一个变量为好。我试着用和的strstr不过的strcat没有sucess。

 ,而((C =的getchar())!= EOF)
{
    的printf(%C,C);
}
返回0;


解决方案

您将需要一个以上的字符来存储一行。例如使用字符数组,像这样:

 的#define MAX_LINE 256
焦线[MAX_LINE]
INT line_length = 0;//循环直到的getchar()返回EOF
//检查不超过线阵列, - 1,以腾出空间
//为NUL终结者
而((C =的getchar())= EOF和放大器;&安培; line_length< MAX_LINE - 1!){  行[line_length] = C;
  line_length ++;
  //上面的两行可以更惯用的组合:
  //行[line_length ++] = C;
}
 //终止阵列,所以它可被用作一个串
线[line_length] = 0;
的printf(%S \\ n,行);
返回0;

有了这个,你看不懂不是一个固定大小(255在这种情况下)更长的线路。 K&安培; R将教你动态分配的内存以后,你可以用它来阅读arbitarly长行

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;

解决方案

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.

这篇关于的getchar()和逐行读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆