简体   繁体   中英

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.

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. Without those braces, the only thing inside the while is the first if statement. 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.

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 :-)

If you put a opening brace after the while and a closing brace before the printf , it should count everything.

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. Your 2nd and third if statements wouldn't indent as far as they are.

Another alternative, if you dislike braces, is to use else if where you use if . Don't do that, but do understand it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM