【发布时间】:2013-01-19 06:20:57
【问题描述】:
我只是编程的初学者。我正在学习 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 个字符)。
我想知道为什么会这样?
【问题讨论】:
-
输入被缓冲,你的程序只有在用户输入换行符后才会接收它(或者如果系统缓冲区已满)。
-
为什么这个标签是
C++? -
从表面上看,这个问题与 C++ 无关。
-
@DanielFischer 谢谢。我现在有点明白了。但是为什么不改变 buff[] 字符串呢?计算机不仅可以打印一个 buff[] 字符串,而我认为只有最新更新的 buff[] 字符串可以保留。程序中只定义了一个 buff[] 字符串。或者我可以说,整个结果都被抛光了,只是等待换行符显示出来?
标签: c input inputstream getchar