私はプログラミングの初心者です。そして私はK&Rの本であるCプログラミング言語を学んでいます。私が読んでいる間、私はこの質問にますます興味を持ちます-入力から文字を1つずつ取得するループがあり、出力関数をループに入れると、その結果は各文字を印刷するようなものになると思いました入力直後。ただし、結果として、キーをタップした後にのみ、コンピューターは文字のパッケージ全体を印刷するように見えます。
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文字を入力した直後に(まだENTERキーをタップしていないのに)、長さが80の1行の文字だけを出力するようなものになると思いました。ただし、そのようには表示されません。文字数に関係なく、文字列全体を完全に入力できます。最終的に行を終了することにしたとき、Enterキーをタップするだけで、正しい出力が得られます。長い文字列は、80文字の短い断片/行にカットされます(もちろん、最後の文字列にはそれより少ない文字が含まれる場合があります)。 80文字以上)。
なぜそれが起こったのだろうか?