[英]I am using turbo C++ and my program is producing no output
The title pretty much says it all, so here's the code: 标题几乎说明了一切,所以这里是代码:
#include <stdio.h>
/* Program counts blanks, tabs, and newlines */
int main(void)
{
int c;
int b, t, nl;
b = 0;
t = 0;
nl = 0;
while ((c = getchar()) != EOF)
if (c == ' ')
++b;
if (c == '\t')
++t;
if (c == '\n')
++nl;
printf("Input has %d blanks, %d tabs, and %d newlines\n", b, t, nl);
return 0;
}
I don't understand why this doesn't work. 我不明白为什么这不起作用。 It counts the blanks no problem, but then when it comes to the rest their values always get printed as 0. 它计算空白没有问题,但是当涉及到其余部分时,它们的值总是被打印为0。
More than a "here's how it should be" answer, I'd really like a "it doesn't work because... you need to do this because..." answer please. 不仅仅是“这里应该如何”的答案,我真的很喜欢“它不起作用,因为......你需要这样做,因为......”请回答。 I'm trying to grasp the concepts and actually understand the language more than just know what works and what doesn't. 我正在努力掌握这些概念并实际理解语言,而不仅仅是知道哪些有效,哪些无效。
Thanks! 谢谢! You guys have been already helped tons :). 你们已经帮助了吨:)。
It's because you're missing braces for your while
loop. 这是因为你缺少while
循环的大括号。 Without those braces, the only thing inside the while
is the first if
statement. 如果没有这些括号,里面的唯一的事情while
是第一个if
语句。 That's why it's only counting blanks, because you go through the whole file doing that one if
statement then, after exiting the loop, c
is EOF
so neither of the other two if
statements will be true. 这就是为什么它是只计算空白,因为你经历了整个文件做一个 if
声明的话,退出循环后, c
是EOF
所以其他两个既不if
语句为真。
That was a tricky one, it's hard to see because the indentation looks like it should work but, unlike Python, the compiler doesn't use indentation to figure out where things are :-) 这是一个棘手的问题,很难看到因为缩进看起来应该可以工作但是,与Python不同,编译器不会使用缩进来弄清楚事情的位置:-)
If you put a opening brace after the while
and a closing brace before the printf
, it should count everything. 如果你在while
之后放一个左大括号,在printf
之前放一个右大括号,它应该算一切。
In other words, this is what your compiler sees: 换句话说,这是您的编译器所看到的:
while ((c = getchar()) != EOF) {
if (c == ' ')
++b;
}
if (c == '\t')
++t;
if (c == '\n')
++nl;
whereas you want: 而你想要:
while ((c = getchar()) != EOF) {
if (c == ' ')
++b;
if (c == '\t')
++t;
if (c == '\n')
++nl;
}
I see a lot of "always require braces" here. 我在这里看到很多“总是需要大括号”。 That's fine, and it will prevent this from happening, but I tend to prefer to always use a good editor. 这很好,它会阻止这种情况发生,但我倾向于总是使用一个好的编辑器。 Emacs, for example, will automatically indent C code to make this sort of thing very obvious. 例如,Emacs会自动缩进C代码,使这种事情变得非常明显。 Your 2nd and third if
statements wouldn't indent as far as they are. 你的第二和第三个if
语句不会缩进。
Another alternative, if you dislike braces, is to use else if
where you use if
. 如果您不喜欢大括号,另一种选择是使用else if
您使用if
。 Don't do that, but do understand it. 不要这样做,但要明白它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.