O.K. I actually have a found a way to count words in a string... but I couldn't figure out a logic for it.
Here's the code
[code]
#include #include int main(void)
{
char input01[255] = "This is just a test";
char input02[255] = "This is another test";
char *p;
p = strtok(input01, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
p = strtok(input02, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
p = strtok(NULL, " ");
if (p) printf("%s
", p);
}
[/code]
So how do I convert this code so, that it uses a while loop to count how many words in the string are with strtok ???
Comments
:
: Here's the code
: [code]
: #include
: #include
:
: int main(void)
: {
: char input01[255] = "This is just a test";
: char input02[255] = "This is another test";
: char *p;
:
: p = strtok(input01, " ");
: if (p) printf("%s
", p);
:
: So how do I convert this code so, that it uses a while loop to count how many words in the string are with strtok ???
:
Use a while loop like this:
p = strok(input01, " ");
while(p) {
printf("%s
", p);
p = strtok(NULL, " ");
}
Rod
: :
: : Here's the code
: : [code]
: : #include
: : #include
: :
: : int main(void)
: : {
: : char input01[255] = "This is just a test";
: : char input02[255] = "This is another test";
: : char *p;
: :
: : p = strtok(input01, " ");
: : if (p) printf("%s
", p);
: : [/code]
:
: : So how do I convert this code so, that it uses a while loop to count how many words in the string are with strtok ???
: :
:
: Use a while loop like this:
: [code]
: p = strok(input01, " ");
:
: while(p) {
: printf("%s
", p);
: p = strtok(NULL, " ");
: }
: [/code]
You could also use a for loop:
[code=ffffff]
for ( p = strtok(input01, " "); p; p = strtok((char *)0, " ") ) {
puts(p);
}
[/code]
Of course, this is more of a style issue than anything, but the for loop is made for situations just like these.
Note that it is a good idea to cast the NULL macro, or 0 (whichever you prefer for null pointer constants) when using them as a function argument. Check the C FAQ section 5 for more (second link in my sig).
HTH,
Will
--
http://www.tuxedo.org/~esr/faqs/smart-questions.html
http://www.eskimo.com/~scs/C-faq/top.html
http://www.parashift.com/c++-faq-lite/
http://www.accu.org/
That was exactly what I was looking for Thanks again !
with my best regards
Client