I made a very simple C program that is supposed to count how many characters and words are in a string (I count words by checking how many spaces are in the text and one to it). The current code is the following (with no ‘printf’s to keep it shorter):
int main(int argc, char *argv[])
{
int character;
int words, characters = 0;
while ((character = getchar()) != '\n') {
characters = ++characters;
if ((character == ' ') || (character == '\d')) {
words = ++words;
}
}
return 0;
}
My problem is that counting words do not work. I get an accurate count for characters, but words always gives me 2293576, and I cannot for the world figure out why.
Can someone solve this mystery for me?
Thank you for all your answers; I really appreciate the help.
and sorry if my primitive skills made some of your heads hurt. I am a beginner but hopefully improve fast.
You haven’t initialized
words. Uninitialized local variables in C default to an undefined value and are not automatically initialized to zero.The statement
Is not the same as