我正在学习c语言,程序是关于计算字符数的。
这是代码
#include <stdio.h>
int main(void) {
// your code goes here
double nc;
for (nc=0;getchar() != EOF;nc++);
printf("%.0f\n", nc);
return 0;
}
输入
''
不输入。
我得到的输出是 1。
在线编译器 result
不应输出等于 0,而不是 1。无法理解为什么会这样。
谢谢
最佳答案
如果您在编程中多加努力,添加几行代码,一切都会很清楚:
#include <stdio.h>
int main(void) {
// your code goes here
int nc;
int c;
for (nc=0;(c = getchar()) != EOF;nc++)
{
printf("The char is '%c' code: 0x%02x\n", c >= 32 ? c : '.', c);
}
printf("%d\n", nc);
return 0;
}
谜团解开了。您已在 ideone 输入框中按了回车键,那里有一个新行。
关于c - 使用for循环计算c中的字长时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56851809/