【问题标题】:Telephone directory program using 2D array in c++C++中使用二维数组的电话簿程序
【发布时间】:2017-04-14 00:00:30
【问题描述】:

我得到了以下任务

编写一个简单的电话簿程序;包含二维数组,其中有硬代码名称和电话号码。然后声明一个简单的字符数组。您必须提示用户输入您要搜索的任何名称。这个名字应该存储在这个字符数组中,然后从二维数组中搜索这个名字。如果在输入的名称中找到数字,则程序应根据该名称显示该数字,如果未找到,则程序应显示该名称未注册的消息。

这是我的代码,但我在搜索名称时找不到号码。我是编码新手,因此无法使此代码正常工作。感谢您的帮助。

#include <iostream>
#include <conio.h>
using namespace std;

int getPhone(int p[5][10],int row, int col, char key[10],char n[5][10]);

int main() {
    int i,j;
    char search[10];
    const int r = 5;
    const int c = 10;
    int element;
    int phone[r][c] = 
    {
    42-5429874,
    42-5333156,
    42-9824617,
    42-9927562,
    42-6238175
    };

    char name[r][c] = {"shazia","zara","sana","ahmad","maha"};
    cout<<"\nEnter name to find in directory : ";
    cin>>search[r];

    element = getPhone(phone,r,c,search,name);
    cin.get();  
    return 0;
    }

int getPhone(int p[5][10],int row,int col,char key[10], char n[5][10]) {
    int i, j;
    for(i=0;i<row;i++)
     for(j=0;j<col;j++)
       p[5][10] = p[i][j];
    if(key[j] = n[5][10])
         cout<<"The desired number is: "<<p[i][j]<<endl;
         else if(key[j]!=n[5][10])
         cout<<"Sorry! This name is not registered."; 

     return p[i][j];
}

【问题讨论】:

  • 你的 GetPhone 完全是一派胡言。
  • search 是 10 个chars 的数组,所以search[r]rth charsearch。强调一个它是一个charcin&gt;&gt;search[r] 只读取一个字符并将其放在rth char in search 中。没有人能说出search 中的其他 9 个字符是什么,因为它们没有被赋予任何值。

标签: c++ arrays search directory 2d


【解决方案1】:

您的代码包含几个错误。让我们检查一下。

for(i=0;i<row;i++)
    for(j=0;j<col;j++)
        p[5][10] = p[i][j];

在这里,您没有对数组进行任何更改,因为只是更改了 p[5][10] 的值。此外,您访问的内存区域无效,因为在 C++ 中,数组索引从 0 变为 size - 1。所以最后一个索引是p[4][9]

if(key[j] = n[5][10])

在 C++ 中,比较两个值需要两个 =,因为只有一个是导致 if 始终为真的做作。要记住的提示:要比较的两个值需要两个 =

else if(key[j]!=n[5][10])

和以前一样,你访问了无效的内存区域。你确定 j 是有效的,例如小于 10 吗?如果没有,你会做双重无效访问。

cin>>search[r];

由于searchchar 的数组,因此您在那里只输入一个char,我认为这不是您想要的,这可能会导致段错误。

int phone[r][c] = 
    {
    42-5429874,
    42-5333156,
    42-9824617,
    42-9927562,
    42-6238175
    };

你的数组不好,一个简单的一维数组就够了,不是二维的。此外,42-54.. 做了减法,我认为这不是你想要的。

还有其他错误。但为什么不使用 C++ 抽象,例如 std::vectorstd::string?你的生活会变得容易得多。但我猜你有一位老老师,从不花时间学习 C++ 新闻,或者那不是一位好老师。

作为初学者,我建议您阅读C++ PrimerProgramming: Principles and Practice Using C++,向您介绍编程和现代C++。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2011-09-13
    相关资源
    最近更新 更多