使用字符串数组从书籍列表中查找书籍
Posted
技术标签:
【中文标题】使用字符串数组从书籍列表中查找书籍【英文标题】:Finding a book from a list of books using string array 【发布时间】:2021-06-09 09:59:34 【问题描述】:问题是检查是否在书籍列表中找到了特定书籍。 我知道如何直接做,但需要使用指针。 请帮我调试第二个代码。
#include <iostream>
#include<string.h>
using namespace std;
int main()
int n,i,c=0;
char A[10][100],s[10];
cout<<"Enter no:of books: ";
cin>>n;
for(i=0;i<n;i++)
cin>>A[i];
cout<<"Enter book you want to search: ";
cin>>s;
for(i=0;i<n;i++)
if(strcmp(A[i],s)==0)
c++;
if(c==0)
cout<<"Not found";
else
cout<<"Book found";
我想用指针来做这件事。请帮帮我
我试过这个:
#include <iostream>
#include<string.h>
using namespace std;
int main()
int n,i,c=0;
char A[10][100],s[10];
const char *p[10][100];
cout<<"Enter no:of books: ";
cin>>n;
for(i=0;i<n;i++)
cin>>A[i];
cout<<"Enter book you want to search: ";
cin>>s;
p=&A[0];
for(i=0;i<n;i++)
if(strcmp(*p,s)==0)
c++;
p++;
if(c==0)
cout<<"Not found";
else
cout<<"Book found";
但不工作
【问题讨论】:
【参考方案1】:从const char *p[10][100];
切换到char (*p)[100];
将解决问题:
#include <iostream>
#include <string.h>
using namespace std;
int main()
int n,i,c=0;
char A[10][100],s[10];
char (*p)[100];
cout<<"Enter no. of books: ";
cin>>n;
for(i=0; i<n; i++) cout << "Enter book name : "; cin>>A[i];
cout<<"Enter book you want to search: ";
cin>>s;
p = &A[0];
for(i=0; i<n; i++)
if(strcmp(*p,s)==0)
c++;
p++;
if(c==0)
cout<<"Not found";
else
cout<<"Book found";
结果:
Enter no. of books: 3
Enter book name : abc
Enter book name : def
Enter book name : ghi
Enter book you want to search: abc
Book found
为什么会这样?
首先,char *p[10][100]
将声明一个指针数组,而char *p[100]
只声明一个指针数组。
其次,char *p[100]
声明一个指针数组,而char (p*) [100]
声明一个指向char[]
数组的指针。注意array of pointers
到pointer to array
。
另外,请参阅Why is "using namespace std;" considered bad practice?
相关:pointer to array c++
【讨论】:
以上是关于使用字符串数组从书籍列表中查找书籍的主要内容,如果未能解决你的问题,请参考以下文章