【问题标题】: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";
}

但不工作

【问题讨论】:

    标签: c++ pointers


    【解决方案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 pointerspointer to array

    另外,请参阅Why is "using namespace std;" considered bad practice?

    相关:pointer to array c++

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 2021-04-30
      • 1970-01-01
      • 2021-01-06
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多