gk245 <to*****@mail.com> writes:
Basically, i want to make a function that will receive a sentence or
phrase, and count its words.
It would start like this (i think):
#include <stdio.h>
int count ( char sentence [] )
{
char string [100];
printf("Enter sentence: ");
scanf() //not sure if this is the right thing to do..
etc...
}
Problem is that i am not sure if there are any functions that make
this easier. I looked at fgets() but that one wants a file. Also,
what happens if someone puts in a long sentence? I mean, the size of
the array would be a fixed size in the function, no?
How does your count() function get the string that it's going to
process? It looks like you're passing it in as a parameter
"char sentence[]" *and* reading it from stdin (char string[100]).
Do one or the other, not both.
The best approach is probably to separate obtaining the input from
processing it. fgets() is a good way to read a line of input. Once
you've called fgets() (check whether it succeeded), you have a pointer
to a string; use that to process the data.
To focus on a relatively minor point, this:
int count(char sentence[]);
is exactly equivalent to this:
int count(char *sentence);
You can't really pass an array directly to a function; you can only
pass a pointer through which you can access the array. C allows the
"[]" syntax in a parameter declaration, which makes it look like
you're passing an array; in my opinion, this feature causes more
problems that it solves, and is best avoided. Learn how arrays and
pointers work (section 6 of the comp.lang.c FAQ covers this very
well), and don't try to pretend that arrays are "really" pointers.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.