Mohil Khare Mohil Khare -4 years ago 110
C++ Question

How to search for a word in a char 2D array?

So I am currently working on a project which requires me to take the words of the array from the user and then ask them to search for a word in the array. The program must show the position of the word in the array. Here's what I did:

#include <iostream.h>
#include <conio.h>

main()
{
char studentsList[30][20];
int size, flag = 0, pos;
cout << "Enter the size of the array: ";
cin >> size;
cout << "Enter yhe names of the students: \n";
for(int i = 0; i < size; i++)
{
cout << "Student no. " << i + 1 << ": ";
cin >> studentsList[i];
}
for(int m = 0; m < size; m++)
{
cout << studentsList[m] << "\t";
}
char searchName[20];
cout << "type the name you need to search: ";
cin >> searchName;
for(i = 0; i < size; i++)
{
if(studentsList[i] == searchName)
{
flag = 1;
pos = i + 1;
}
}
if(flag == 0)
cout << "Term not found.";
else
cout << "Term found at position " << pos;
getch();
}


I am not able to catch what's wrong in the code. It always gives the output as 'Term not found.' Help will be appreciated!

Answer Source

I think the problem is on the way you are using equality check.

it is in if(studentsList[i] == searchName)

The == is comparing the memory address. Instead, since you are using char[] it is better to make a utility function to check the equality char by char.

void arrcmp( unsigned char arr1[], unsigned char arr2[] )
{
    int i = 0;
    int match = 0;

    for( i=0; i < 8; ++i ) {
        if( arr1[i] != arr2[i] ){
            match = 1;
            break;
        }
    }

    return match==0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download