Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

beginners question; very basic wc.c will not compile?

Status
Not open for further replies.

twintriode

Technical User
Jan 6, 2005
21
AU
Hi all,

I am really new to c, and I am stepping through a C manual, the "Prentice Hall, C Programming Language" book and I am having frustrating problems with alot of the early examples.

Like this simple word count program will not compile:

Code:
#include <stdio.h>

#define IN 1
#define OUT 2

main ( )
{
	int c, nl, nw, nc, state;
	
	state = OUT;
	nl = nw = nc = 0;
	while ( (c = getchar ( ) ) != EOF) {

		++nc;
		if ( c == '\n')
			++nl;
		if (c == '  '  | | c == '\n'  | | c = '\t' )
			state = OUT;
		else if (state == OUT) {
			state = IN;
			++nw;
		}
	}
	printf ("%d %d %d\n", nl, nw, nc);
}

gives the error:

$ cc wc.c -o wc
wc.c:19:26: warning: multi-character character constant
wc.c: In function `main':
wc.c:19: error: syntax error before '|' token
wc.c: At top level:
wc.c:26: error: syntax error before string constant
wc.c:26: warning: conflicting types for built-in function `printf'wc.c:26: warning: data definition has no type or storage class


What is going on here? Could this be because the book I am using may already be outdated?

Also the following program does not seem to be doing what the book said it is supposed to:

Code:
#include <stdio.h>

main ( )

{

int c, nl;

nl = 0;
while ( (c = getchar ( ) ) != EOF )
	if ( c == ' \n ' ) 
		++nl;
	printf ( "%d\n" , nl);
}

just reads

$ ./put3
this
does
not
seem
to
be
working?

but no line count or anything.

Can anybody point out what I am doing wrong here?
 
1) The or symbol is || with no space in between
2) When specifying characters, there should be no spaces surrounding the character, except when it is a space. i.e.
Code:
'\n'    correct
' \n '  wrong
You have 2 spaces in ' ': it should only be one space
 
thanks for the reply. I changed what you suggested and also noticed I was missing an = sign in one of the lines. So now the word count program compiles, but it does nothing?? No word count, it just takes input and thats it??

Code:
#include <stdio.h>

#define IN 1
#define OUT 2

main ( )
{
	int c, nl, nw, nc, state;
	
	state = OUT;
	nl = nw = nc = 0;
	while ((c = getchar ( )) != EOF) {

		++nc;
		if (c == '\n')
			++nl;
		if (c == ' ' || c == '\n' || c == '\t')
			state = OUT;
		else if (state == OUT) {
			state = IN;
			++nw;
		}
	}
	printf("%d %d %d\n", nl, nw, nc);
}
 
Depending on your OS and/or terminal, you typically have to press CTRL-D or CTRL-Z at the start of a line to send an EOF to your program.

--
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top