3

When running the program provided in chapter 1.6 Arrays of The C Programming Language I get some very inconsistent results from the final printf.

Here is the program:

#include <stdio.h>

int main()
{
  int c, i, nwhite, nother;
  int ndigit[10];

  nwhite = nother = 0;

  for (i = 0; i < 10; ++i)
    ndigit[i] = 0;

  while ((c = getchar()) != EOF)
  {
    if (c >= '0' && c <= '9')
        ++ndigit[c-'0'];
    else if (c == ' ' || c == '\n' || c == '\t')
        ++nwhite;
    else
        ++nother;
  }

  printf("digits =");

  for (i = 0; i < 10; ++i)      
    printf(" %d", ndigit[i]);

  printf(" white space = %d \n nother = %d \n", nwhite, nother);
}

Here's the execution: Windows PowerShell

I'm greatly confused by the apparent randomness of it. I'd be very grateful to anyone who can highlight what I'm missing here, especially considering this isn't even a program of my own making: this is provided by the book itself.

Thank you.


EDIT:

I've tried running the program in Command Prompt as opposed to Windows PowerShell. No difference in the results.

Also I've tried adding an int at the beginning of the main

  int k = 99;

and two printf's, before and after, the final printf

  printf("%d", k);
  printf(" white space = %d \n nother = %d \n", nwhite, nother);
  printf("%d", k);

Only the first one of the two extra printf's is printed but at the expense of 2 more characters from the middle one.

htskll
  • 31
  • 3
  • 2
    The code seems to be working fine, as to why the final `printf` gets truncated, that's hard to say. It could have something to do with PowerShell. – Qubit Dec 05 '18 at 14:45
  • 2
    Try adding [`fflush(stdout);`](https://stackoverflow.com/a/1716621/243245) to the end, although I'm not sure why you'd need that. – Rup Dec 05 '18 at 14:47
  • 1
    Your code is correct and should work, like [here](http://tpcg.io/J1VCv8) it does. Strange. – KamilCuk Dec 05 '18 at 14:47
  • 1
    Try running it outside of powershell. – Retired Ninja Dec 05 '18 at 14:48
  • 3
    What compiler are you using? You might try adding an explicit `return 0` at the end. – Retired Ninja Dec 05 '18 at 15:10
  • @RetiredNinja If I understood your question correctly then it's "MinGW32-base". I've tried adding `return 0;` as I usually do for my programs (this was copied from the book) but it made no difference. – htskll Dec 05 '18 at 15:59
  • 1
    Something is broken in your compiler or the environment. the code is correct. Try running under MSYS/MinGw console – Eugene Sh. Dec 05 '18 at 16:02

0 Answers0