[Courses] [C] Lesson 8 answer on word counter
Morgon Kanter
admin at surgo.net
Sun Nov 10 16:46:15 EST 2002
This thing segfaulted until I realized that i was uninitialized before use.
The C compiler doesn't catch that like the Java one does =)
#include <stdio.h>
int words(char string[]) {
int i = 0;
int returnvalue = 0;
while(1) {
if((i == 0) && string[i] == '\0')) break;
if ((string[i] == '\0') || (string[i] == ' ')) {
returnvalue++;
i++;
}
else i++;
}
return returnvalue;
}
main() {
char line[80];
int words_in_line;
printf("Please enter a string: ");
fgets(line, sizeof(line), stdin);
words_in_line = words(line);
printf("%d\n", words_in_line);
}
More information about the Courses
mailing list