I have a runtime error that i cant figure out (SOLVED)

Started by
13 comments, last by Kylotan 18 years ago
Thaks for all your help.

and yes I am trying to count the characters in the file.

and it works perfectly. The error doesn't come until the program reaches literally the end. In debug it breaks after the closing perenthasis of main().
I think you were right when you said that I am trying to put a non char into the chbuf. I changed the section in question to the following and it fixed it.

while(!infile.eof())	{		chbuf = infile.get();			if(unsigned char(chbuf) <256)		chCount[unsigned char(chbuf)]++;	}



and instead of saying "this is a perfect example of how not to do something. why dont you give the right example. This is the for beginners message board after all. why post here if you not a beginner or not someone who would like to help beginners?
These tears..leave scars...as they run down my face.
Advertisement
Quote:Original post by Dave
Hey bud,

At first guess i would say that it is because you have a char array of length 256 but are only setting the first element, upon initialisation.

Dave


actually the following does initialize every element in the array to 0 or whatever you put in the perens.
just FYI. :)

long chCount[256]= {0};
These tears..leave scars...as they run down my face.
Quote:and instead of saying "this is a perfect example of how not to do something. why dont you give the right example.


I was talking about simon10k's code, and I don't think I need to provide an example of how to read data from a file into a buffer.
my mistake sorry :)
These tears..leave scars...as they run down my face.
Quote:Original post by donjonson
Thaks for all your help.

and yes I am trying to count the characters in the file.

and it works perfectly.


By the way, you still have a couple of subtle bugs, that you may never notice but I'll share anyway.

.get can return EOF, as I said earlier. However, by that point you have already read in that value, and you'd try to count it in your array, which is not generally what you want to do.

Also, because you cast the value to an unsigned char, there is no point comparing them against 256, because every unsigned char is less than 256. So your if statement achieves nothing. One better way to write such a loop would be like so:
int chbuf;while((chbuf = infile.get()) != EOF){    ++chCount[unsigned char(chbuf)];}


Note that I also changed it to use pre-increment instead of post-increment. It's a good habit to get into using pre-increment where possible because it can be quicker than post-increment on some objects.

This topic is closed to new replies.

Advertisement