【发布时间】:2017-03-19 13:05:42
【问题描述】:
这是我在“C 编程语言”中练习 1-13 的代码:
#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: ||-----
为了清楚起见,我只在按“Enter”时从 printf() 和 putchar() 获得输出。 CTRL-D 只是结束循环和程序。
【问题讨论】:
-
您使用的是 Windows 吗?它有不同的行尾。它使用
\r\n -
不,我在 Ubuntu 16.04 上。
标签: c