Im trying to write a program to count characters and words when type a sentence but i keep getting "syntax error : missing ';' before 'type'" as an error. Anyone see where I'm going wrong? Thanks

#include <stdio.h>
#include <ctype.h>
int found_word(void);

int main()
{
	int c, nw=0, nc=0;
		
	printf("Enter a sentence>");

	while (found_word() == 1)
		++nw;

	while ((c = getchar()) != EOF) {
		if(isalpha(c))
			++nc;
		}

	int found_word(void)
	{
		int c;

		while (isspace(c=getchar()))
			;
		if (c != EOF) {
			while ((c =getchar()) != EOF && !isspace(c))
				;
			return 1;
		}
	
	printf("Number of words      = %d\n", nw);
	printf("Number of characters = %d\n", nc);

	return 0;

}

Recommended Answers

All 5 Replies

You've defined your function inside main.

Cheers. Didn't see that. It runs now but when i type in a sentence i need to type 2 EOF commands and now it counts words and gives 0 for characters.!

>It runs now but when i type in a sentence i need to type 2 EOF commands and now it counts words and gives 0 for characters.
Logic flaw you introduced had.

while (found_word() == 1)
		++nw;

Here you read everyone of what you loosely call word, going through the sentence given to standard input.
And then

while ((c = getchar()) != EOF) {
		if(isalpha(c))
			++nc;
		}

you ask to read more from input. But there's nothing. It is waiting for someone to input something.

Got rid of the function found_word and changed code to this.

#include <stdio.h>
#include <ctype.h>
int found_word(void);

int main()
{
	int c, nw=0, nc=0;
	int lastChar=0;
		
	printf("Enter a sentence>");

	while ((c = getchar()) != EOF) {
		if(isalpha(c))
			++nc;
		if (lastChar && (c == '\n' || c == '\t' || c == ' ' || c == ',' || c == '.' ))
			++nw;
			lastChar=isalnum(c);
		}
		

	printf("Number of Words = %d\n", nw);
	printf("Number of Regular Letters = %d\n", nc);


	return 0;

}

Seems to work ok even if it is a bit long winded in the middle

You might be able to use the built-in functions ispunct() and isspace() to 'tone down' some of the long windedness.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.