нет результата вывода при поиске массива или отображении массива - PullRequest
0 голосов
/ 05 ноября 2011

Я создаю список, который позволяет мне вводить данные, а затем искать или отображать введенные данные. По какой-то причине я не могу произвести вывод. Проблема может быть в функции вывода. Как я могу это исправить? Вот код:

#include<iostream>
#include<string>
#include<cstdlib>
#include <stdio.h>
#include <string.h>

using namespace std;

class contact{
private:
  string fn;
  string ln;
  string email;
  string number;
public:
  // Accessor and Mutator method for contacts variable
  void setfname(string f_n);
  string getfname();
  void setlname(string l_n);
  string getlname();
  void setemail(string emaila);
  string getemail();
  void setnumber(string num);
  string getnumber();
  // takes input entered for contacts
  void input();
  // display output
  void output();
  contact();

  contact(string f_n, string l_n, string emaila,string num);
};

void menu();
void EnterContact(contact contacts[], int size, int& numberUsed);
void show(contact contacts[], int sizeOfa);
int search_contacts(contact contacts[], string& lastname, int& size);

int main(){
  string opt="";
  const int MAX=2;
  int size;
  contact contacts[MAX];
  contact c[MAX];
  for(int i=0; i<MAX; i++){
    EnterContact(contacts, MAX, size);
  }
  menu();

  return 0;
}

//use these variables globally
const int MAX = 2;
contact contacts[MAX];

void EnterContact(contact contacts[], int size, int& numberUsed)
{
  char ans;
  bool done = false;
  int index = 0;
  cout << "Enter up to " << size << endl;
  while ((!done) && (index < size))
  {
    contacts[index].input();
    cout << "Do you want to add another contact?(y/n followed by Return): ";
    cin >> ans;
    if ((ans == 'y') && (ans == 'Y'))
      index++;
    else
      done = true;
  }
  numberUsed = index+1;
}

int search_contacts(contact contacts[], string& lastname, int& size)
{
  int index = 0;
  bool found = false;
  for(int index=0; index<size ; index++){
    if (lastname == contacts[index].getlname()){
      found = true;
      cout<<"found";
      break;
    }
  }

  if (!found)
    cout<<"no";
  return index;
}
void show(contact contacts[], int sizeOfa)
{
  for (int index = 0; index < sizeOfa; index++)
    contacts[index].output();
}

void menu()
{
  cout<<"\nContact Menu"<<endl;
  cout << "1. Add a New Contact. " << endl;
  cout << "2. Search for a Contact. " << endl;
  cout << "3. Delete Contact from list. " << endl;
  cout << "4. View All Contacts. " << endl;
  cout << "5. Exit the program. " << endl;
  cout << "Enter your choice: ";
  int opt; int result, a; char ans; string lastname;
  cin>>opt;
  switch (opt)
  {
  case 1: cout<<"func to Add a New Contact"<<endl;
    cout<<"\nAdd another contact";
    break;
  case 2:
    do
    {
      cout << "\nSearch contact by lastname: ";
      cin >> lastname;
      result = search_contacts(contacts, lastname, result);
      if (result == -1)
        cout << lastname << " Contact not found.\n";
      else
        contacts[result].output();

      cout << lastname << " is stored in array position "<< result << endl;
      cout << "Search again? (y/n): ";
      cin >> ans;
    } while ((ans != 'n') && (ans != 'N'));
    menu();
    break;
  case 3: cout<<"func to Delete Contact from list";
    break;
  case 4: cout<<"\nAll Contacts"<<endl;
    show(contacts, MAX);
    cout<<endl;
    menu();
    break;
  case 5: cout<<"\nContact Book is closed"<<endl;
    exit(1);
    break;
  default: cout<<"\nInvalid entry...Closing Contact Book"<<endl;
  }
}
contact::contact()
{
  fn=""; ln=""; email=""; number="";
}
contact::contact(string f_n, string l_n, string emaila,string num)
{
  fn= f_n; ln= l_n; email= emaila;number= num;
}
void contact::input()
{
  cout<<"\nFirst Name: ";
  cin>>fn;
  cout<<"Last Name: ";
  cin>>ln;
  cout<<"Email: ";
  cin>>email;
  cout<<"Phone number: ";
  cin>>number;
}

void contact::output()
{
  cout<<"\nName: "<<fn<<" "<<ln;
  cout<<"\nEmail: "<<email;
  cout<<"\nPhone number: "<<number;
  cout<<endl;
}
void contact::setfname(string f_n)
{
  fn= f_n;
}
string contact::getfname();
{
  return fn;
}
void contact::setlname(string l_n)
{
  ln= l_n;
}
string contact::getlname()
{
  return ln;
}
void contact::setemail(string emaila)
{
  email= emaila;
}
string contact::getemail()
{
  return email;
}
void contact::setnumber(string num)
{
  number= num;
}
string contact::getnumber()
{
  return number;
}

Ответы [ 3 ]

2 голосов
/ 09 ноября 2011

Ваша проблема в том, как вы используете функцию меню, попробуйте использовать меню выбора в основной функции, а не объявлять ее как функцию. если вы хотите использовать его как функцию, рассмотрите возможность использования оператора if else. это должно заботиться о вашем вводе и выводе.

int main(){
  string opt="";
  const int MAX=2;
  int size;
  contact contacts[MAX];
contact c[MAX];
for(int i=0; i<MAX; i++){
  EnterContact(contacts, MAX, size);
}
cout<<"\nContact Menu"<<endl;
cout << "1. Add a New Contact. " << endl;
cout << "2. Search for a Contact. " << endl;
cout << "3. Delete Contact from list. " << endl;
cout << "4. View All Contacts. " << endl;
cout << "5. Exit the program. " << endl;
cout << "Enter your choice: ";
int opt; int result, a; char ans; string lastname;
cin>>opt;
switch (opt)
{
case 1: cout<<"func to Add a New Contact"<<endl;
  cout<<"\nAdd another contact";
  break;
case 2:
  do
  {
    cout << "\nSearch contact by lastname: ";
    cin >> lastname;
    result = search_contacts(contacts, lastname, result);
   if (result == -1)
     cout << lastname << " Contact not found.\n";
   else
     contacts[result].output();

   cout << lastname << " is stored in array position "<< result << endl;
   cout << "Search again? (y/n): ";
   cin >> ans;
 } while ((ans != 'n') && (ans != 'N'));
 menu();
 break;
case 3: cout<<"func to Delete Contact from list";
 break;
case 4: cout<<"\nAll Contacts"<<endl;
 show(contacts, MAX);
cout<<endl;
menu();
break;
case 5: cout<<"\nContact Book is closed"<<endl;
exit(1);
break;
default: cout<<"\nInvalid entry...Closing Contact Book"<<endl;
}
return 0;

}

также у вас уже есть функция, которая заботится о вашем вводе, вам не нужно помещать его в цикл for в основной функции.

1 голос
/ 05 ноября 2011

В вашей программе несколько ошибок.То, что мешает вам отображать список контактов, это:

У вас есть две переменные с именем contacts.Во-первых, у вас есть локальная переменная в main(), объявленная таким образом:

  contact contacts[MAX];

Затем у вас есть глобальная переменная, объявленная сразу после main(), таким образом:

contact contacts[MAX];

Эти две переменныеразличны - они никак не связаны, кроме как случайно по имени.EnterContact записывает в один из массивов, но show отображает значения из другого.

Вероятно, вам следует переместить все ваши глобальные объявления до любого из вашего кода и удалить с таким же именемдекларации от main().

0 голосов
/ 05 ноября 2011
contact contacts[MAX];  

for(int i=0; i<MAX; i++){
    EnterContact(contacts, MAX, size);
}

Я думаю, вам нужно передать i в функцию EnterContact, чтобы обеспечить ввод для каждого объекта в массиве contacts.На данный момент вы перезаписываете один и тот же объект на каждой итерации цикла.

...