2017-02-27 104 views
-1

因此,我目前正在研究一个项目,该项目需要我从用户那里获取数组的单词,然后让他们搜索数组中的单词。程序必须显示数组中单词的位置。以下是我所做的:如何搜索字符二维数组中的单词?

#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(); 
} 

我无法捕捉代码中的错误。它总是将输出作为'未找到期限'。帮助将不胜感激!

+1

这不是C++。由于几个原因,它不会编译。在修复代码以便编译代码时,可以借助调试器轻松解决问题。 – mpiatek

+4

请参阅[本文](http://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c)了解如何比较C字符串。请注意,如果你使用'std :: string',你的生活会更容易。 – Rakete1111

+0

您使用的头文件都不是标准C++的一部分。无论你从哪里学习这些东西,都要从其他地方学习。 –

回答

-2

我认为问题在于您使用平等检查的方式。

它是if(studentsList[i] == searchName)

的==在比较存储器地址。 相反,由于您使用的是char [],因此最好使用实用函数来检查char的等于char。

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

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

这不会编译。你可能意思是'bool arrcmp'。但是不要重新发明轮子 - 他可以使用'std :: strncmp'或'std :: string'&std :: find' – mpiatek

+0

另外你的实现是完全错误的 - 当字符串短于8时会发生什么?如果他们的时间更长,但第9个角色开始差异会发生什么? – mpiatek

+0

感谢您的意见,只是修复它,对不起,我写得很快:) –