linear search

I'm having the darndest time trying to figure out how to write a function;
The user enters a word and that word is sent to a function that searches a 2-dim array to see if that word has already been entered, if it hasn't, the word is added to the array, if it has, instead of adding the word again, a tally of that particular word increases by 1. this goes on until either 100 "unique" words have been entered or the user enters a blank.

1
2
3
4
5
6
7
8
9
10
11
12
Void searchArray (Word)

{
  for (int i = 0; i < Word.words; i++)  //searches array for word
  {
    if (tempWord.words != Word.words);  //if word is not in array
     strcpy (wordList[occurence], tempWord.words); //????add word to array???
    else
      strcpy wordList[occurence]++;  //????increase occurence of word by 1?????
  }
}
          
I've replied to your original thread. I will post the same reply here:

I suggest using a vector.
http://www.cplusplus.com/reference/stl/vector/vector/

Just push the words into a vector then search for the word in that vector. If it exists then increase the count of that word. Otherwise push that word into the vector.

I also suggest creating a word struct which contains the string value of the word and the count. Use that when inserting into your vector.
 
struct word{int count; string value;};

http://www.cplusplus.com/forum/beginner/4606/
If you don't want to do that. There are some serious logic errors in your code above.

First of all; if you perform the conditional:
1
2
if (tempWord.words != Word.words);  //if word is not in array
     strcpy (wordList[occurence], tempWord.words);

You going to be replacing the same index (occurence) in the array with the same word. I suggest rather using a boolean and just iterate through the array once. If you find the word, increase the word at that index's count. After the for loop, if the value is still false then insert the word into the array.

Second of all,
 
strcpy wordList[occurence]++;

is the incorrect use of that function and your program won't compile.

This leads me to my last problem with your code. What is "Word"? Is it a class, struct, array of integers or strings. I can't surmise what is going further wrong in your code without that information.

One more thing. Please state your exact problem in your code and where it is going wrong. It will save us a lot of time in deciphering your code.
Last edited on
it's also not going to compile because of the function header. if Word is a variable, you need to include the data type.

you also need to declare tempWord, unless it's a global variable
Last edited on
Topic archived. No new replies allowed.