954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how can I write word counter code in another way

hi : )
I wrote this code for count a specific word selected by user in an array
but it have a logic error ..
and also is there another way to write it without using pointer ?


#include<iostream>
using namespace std;


int j,i=0;
const int size=500;
char array1[size],search[100],*cnt;

//------------

void word();//count a specific word select by user

int main()
{

cout<<"**** ..enter your text.. ****"<<endl;
gets(array1);
word();

return 0;
}


void word()
{
int count=0;
cout<<"enter the word that you want to count"<<endl;
cin>>search;
for ( i = 0; i <= 100; ++i ) {
cnt = &array1[ i ];

while ( cnt = strstr( cnt, search ) ) {
++count;
++cnt;
}
}
cout<<count;
}

please, help me :(

nora-s
Newbie Poster
1 post since May 2010
Reputation Points: 10
Solved Threads: 0
 

Why do you need global variables to do this?

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

Look up strings and their manipulative functions. You should be able to split the string into its separate words and count the result.

Ketsuekiame
Master Poster
752 posts since May 2010
Reputation Points: 349
Solved Threads: 107
 

Some other good keywords are "parsing" and "delimiter".

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

Your solution does have a logical error.

Here's what you can think of as an algorithm.

1. set pointer to start of array.
2. use strstr( ) to find the first instance of the word.
3. When the word is found, increment the counter and then the pointer should be then set to the next position to what has been returned from strstr( ).
4. Repeat this in the process (from 2-3) the pointer is set to NULL or 0.

You will realise that the first for loop is unnecessary in your code.

Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
 

Hey, I need help with the same thing except a hit counter for items opened within the program.
It doesn't work at all, and I really need help.

AveBik
Newbie Poster
1 post since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

@ AveBik Start a new thread with your code you have so far and what is wrong with it plus all relevant error codes.

NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: