我只是编程的初学者。我正在学习 K&R 的书,C 编程语言。当我阅读时,我对这个问题越来越好奇——当有一个循环从输入中一个一个地获取字符时,我在循环中放置了一个输出函数,我认为它的结果就像打印每个字符在它被输入之后。但是,结果似乎只有在我点击一个键后计算机才会打印出一整套字符。
如 K&R 书中练习 1-22 的答案:
/* K&R Exercise 1-22 p.34
*
* Write a program to "fold" long input lines into two or more
* shorter lines after the last non-blank character that occurs before the n-th
* column of input. Make sure your program does something intelligent with very
* long lines, and if there are no blanks or tabs before the specified column.
*/
#include <stdio.h>
#define LINE_LENGTH 80
#define TAB '\t'
#define SPACE ' '
#define NEWLINE '\n'
void entab(int);
int main()
{
int i, j, c;
int n = -1; /* The last column with a space. */
char buff[LINE_LENGTH + 1];
for ( i=0; (c = getchar()) != EOF; ++i )
{
/* Save the SPACE to the buffer. */
if ( c == SPACE )
{
buff[i] = c;
}
/* Save the character to the buffer and note its position. */
else
{
n = i;
buff[i] = c;
}
/* Print the line and reset counts if a NEWLINE is encountered. */
if ( c == NEWLINE )
{
buff[i+1] = '\0';
printf("%s", buff);
n = -1;
i = -1;
}
/* If the LINE_LENGTH was reached instead, then print up to the last
* non-space character. */
else if ( i == LINE_LENGTH - 1 )
{
buff[n+1] = '\0';
printf("%s\n", buff);
n = -1;
i = -1;
}
}
}
我想程序会变成这样,它只会打印出一行字符,长度为 80,就在我输入了 80 个字符之后(我还没有点击 ENTER 键)。然而,它并没有以这种方式出现!无论有多少字符,我都可以完全输入整个字符串。当我最终决定结束这一行时,我只需点击 ENTER 键,它就会给我正确的输出:长字符串被切割成几个短的片段/行,它们有 80 个字符(当然最后一个可能包含更少超过 80 个字符)。
我想知道为什么会这样?