这里是我的锻炼1-13码的“C程序设计语言”:C:为什么在这个代码中“Enter”键触发输出?
#include <stdio.h>
int main()
{
int c, currentIndex, currentLength;
currentLength = currentIndex = 0;
while ((c = getchar()) != EOF){
if (c == '\t' || c == '\n' || c == ' '){
if (currentLength == 0){
continue;
}
printf("Length of word %d: ||", currentIndex);
for (int i = 0; i < currentLength; i++){
putchar('-');
}
putchar('\n');
currentLength = 0;
++currentIndex;
} else {
++currentLength;
}
}
return 0;
}
这样我就可以编译这个与./a.out运行它,但是当我按“Enter”开始新行('\ n')运行printf()和putchar()函数(并且''或'\ t'都不会触发输出)。 while循环没有结束(它会像END-OF-FILE(CTRL-D)那样结束),但我想知道为什么这些函数在被调用时会被调用。它可以防止一次输入多行。下面是一个例子的它的输出:
how long are these words
Length of word 0: ||---
Length of word 1: ||----
Length of word 2: ||---
Length of word 3: ||-----
Length of word 4: ||-----
只是要清楚,我只得到printf()和的putchar()的输出,当我按下“Enter”键。 CTRL-D只是结束循环和程序。
您使用的是Windows吗?它有不同的结局。它使用'\ r \ n' – Mark
不,我在Ubuntu 16.04上。 – jestivus