“不应该输出一次换行符i == 10吗?”
没有。因为控制台输入默认是缓冲的。 getchar() 在找到stdin 中的换行符'\n' 之前不会返回stdin 中的下一个字符。刷新缓冲区需要换行符。
有一些基于实现的解决方案可以立即刷新输入,而不是等待换行符。例如 Windows/DOS 下 conio.h 中的 getche() 或 cbreak() 选项,并在 Linux 的 curses-library 中使用 getch() 而不是 getchar()。
您的计数也不正确,i = 0; 和 if (i == MAXLINE) 在 11 个字符之后将在输出中放置一个换行符,而不是在 10 个字符之后。这是因为您从 0 开始,而不是 1。请改用i = 1 或if (i == (MAXLINE - 1))。
如果您使用的是 Windows/DOS,请尝试:
#include <stdio.h>
#include <conio.h> // Necessary to use getche().
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main (void)
{
int i, c;
for (i = 0; (c = getche()) != EOF; i++)
{
if (i == (MAXLINE - 1))
{
printf("\n");
i = -1; // Counter is reset. To break out of the loop use CTRL + Z.
}
}
//printf("%d\n",i);
}
如果计数器重置对你来说有点难以理解,上面的代码基本上相当于:
#include <stdio.h>
#include <conio.h> // Necessary to use getche().
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main (void)
{
int i, c;
for (i = 1; (c = getche()) != EOF; i++)
{
if (i == MAXLINE)
{
printf("\n");
i = 0; // Counter is reset. To break out of the loop use CTRL + Z.
}
}
//printf("%d\n",i);
}
对于 Linux,请使用 ncurses 库中的 cbreak() 和 getch():
#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main (void)
{
cbreak();
echo();
initscr();
int i, c;
for (i = 1; (c = getch()) != ERR; i++)
{
if (i == MAXLINE)
{
printf("\n");
refresh();
i = 0; // Counter is reset. To break out of the loop use CTRL + D.
}
}
//printf("%d\n",i);
endwin();
}
注意:要使用 ncurses 库,您需要在调用编译器时添加 -lnurses 选项。
此外,您需要使用initscr() 和endwin() 来打开和关闭curses 终端窗口。