I am very new to C++ programming and you will see why.
I want to make a character array consisting of a few words that I want to search with a linear search function. Does this array have to be a two-dimensional array? For example:
char Colors[3][6] = {"red", "green", "blue"};
I tried it like this:
char Colors[] = {"red", "green", "blue"};
This gave me a "too many initializers" error.
I assume the 1st method is correct because it states the amount of elements in the array and the maximum length of an element, correct?
Now how would I implement a linear search function to find a word inside that array? Can I do something like the following:
(Assuming the linearSearch function has already been declared)
char searchKey;
char element;
char Colors[3][6] = {"red", "green", "blue"};
printf("Enter the color to look for: \n");
scanf("%s", searchKey);
element = linearSearch(Colors, searchKey, ??); //?? is where I don't know what to enter
if (element != -1)
{
printf("Found the word.\n");
}
else
{
printf("Didn't find the word.\n");
}
Is this possible? If so, what would the declaration look for the linearSearch function? I hope I provided enough information for this to be somewhat usable.
edit: Thanks all for the help, got the program working as intended.
You could make your linearSearch function to return the index of the search term in the array. Here is a sample program:
#include <stdio.h>
#include <string.h>
int linearSearch (const char **Array, const char *searchKey, int arraySize) {
for (int i = 0; i < arraySize; ++i) {
if (strcmp(Array[i], searchKey) == 0)
return i;
}
// We didn't find the searchKey in the Array
return -1;
}
int main () {
char *colors[] = { "red", "green", "blue" };
int index = linearSearch (colors, "green", 3);
if (index < 0) { // search string was not found
printf("Search string not found!\n");
}
else {
printf("String %s found at index %d\n", colors[index], index);
}
return 0;
}
We use the strcmp() function to compare the strings. It returns zero if strings match and nonzero if they don't. To use it, you need to include the string.h
header.
But, as others have suggested, you should use STL if you can.