2011-02-05 70 views
2

对于我的一个练习,我们需要逐行阅读并仅使用getchar和printf输出。我遵循K & R,其中一个例子显示了使用getchar和putchar。从我读到的,getchar()一次读取一个字符,直到EOF。我想要做的是一次读取一个字符,直到行尾,但存储任何写入char变量的字符。所以如果输入Hello,World !,它会将它全部存储在一个变量中。我试图使用strstr和strcat,但没有成功。getchar()和逐行读取

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

难道你不能在一行中存储所有的字符,只是读取数组的每个字符,直到你有一个空字符? – stanigator 2011-02-05 19:15:38

+0

@stanigator:那么你必须处理内存不足时发生的情况。一种更好的方法是一次忘掉一些行并读取一些中等大小的固定的“N”个字符。 – 2011-02-05 20:29:40

回答

4

您将需要多个字符来存储行。使用例如如下所示:

#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; 

使用此功能,您无法读取长度超过固定大小(本例中为255)的行。 K & R会稍后教会你动态分配的内存,你可以用它来读取长而长的行。