Advertisement

My programs don't output correctly...

Started by September 24, 2002 03:19 PM
1 comment, last by Axensmash 21 years, 11 months ago
Hi there. I have just begun learning the C programming language from the book "The C Programming Language" by Kernighan & Ritchie. I have almost gotten through the 1st chapter but I am noticing a serious problem with the output of my programs. For instance the following program:
  
#include <stdio.h>

/* count digits, white space, others */

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, other = %d\n", nwhite, nother);
}
  
The output should be: digits = [an arrays output], white space = [number of whitespace characters], other = [number of other characters] but instead it outputs: ther = [number of other charatcers] If I put in two or more \n operators in the first printf statement before the word 'digits' the output looks fine. The same also happens in other programs I have gotten from the book. My question is why it does this. I am using the Bloodshed Dev C++ compiler. Any help would be appreciated. Thanks. [edited by - Axensmash on September 24, 2002 5:01:35 PM]
first problem:

nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit = 0;

you are setting the pointer to the head of the array to NULL on each iteration of this loop. what you want is

nwhite = nother = 0;for (i = 0; i < 10; ++i)    ndigit = 0;<br>   </pre>   <br><br>[EDIT: just realized that you probably wrote exactly that but the [ ] brackets didn't show up b/c the web dealio parsed them as formatting commands….]<br><br>-me   <br><br><SPAN CLASS=editedby>[edited by - Palidine &#111;n September 24, 2002 4:23:36 PM]</SPAN>    
Advertisement
That's right. I fixed my previous post so it looks right. But thanks anyway

[edited by - Axensmash on September 24, 2002 5:02:43 PM]

This topic is closed to new replies.

Advertisement