Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在字符2D数组中搜索单词?_C++_Arrays_Multidimensional Array - Fatal编程技术网

C++ 如何在字符2D数组中搜索单词?

C++ 如何在字符2D数组中搜索单词?,c++,arrays,multidimensional-array,C++,Arrays,Multidimensional Array,因此,我目前正在进行一个项目,该项目要求我从用户那里获取数组中的单词,然后让他们在数组中搜索单词。程序必须显示单词在数组中的位置。以下是我所做的: #include <iostream.h> #include <conio.h> main() { char studentsList[30][20]; int size, flag = 0, pos; cout << "Enter the size of the array: "; cin >&g

因此,我目前正在进行一个项目,该项目要求我从用户那里获取数组中的单词,然后让他们在数组中搜索单词。程序必须显示单词在数组中的位置。以下是我所做的:

#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();
}
#包括
#包括
main()
{
char studentsList[30][20];
整数大小,标志=0,位置;
大小;

我想问题出在你使用平等检查的过程中

它位于
if(studentsList[i]==searchName)

==正在比较内存地址。 相反,由于您使用的是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;
}
bool arrcmp(无符号字符arr1[],无符号字符arr2[]{
int i=0;
int匹配=0;
如果(strlen(arr1)!=strlen(arr2)){
返回false;
}
对于(i=0;i这不是C++。它不会编译。由于你的代码修复,所以你的问题可以很容易地在调试代码的帮助下解决。请看如何比较C字符串。注意,如果你使用<代码> STD::String ,你的生活会更容易。你使用的头文件都不是标准C++的一部分。你正在从其他地方学习这些东西。我觉得这个问题每天都会被问一次?daja vu:DOfftopic:1)
main
函数返回
int
。始终。2)
iostream.h
在很久以前已经转换为
iostream
,没有扩展名。这不会编译。你可能会布莱的意思是
bool arrcmp
。但是,不要重新发明轮子-他可以使用
std::strncmp
std::string
&
std::find
同样,您的实现完全错误-当字符串短于8时会发生什么?如果字符串较长,但差异从第9个字符开始会发生什么?谢谢您的评论,朱斯我没修好,抱歉我写得太快了:)