结构问题和程序没有保存输入。我没经验

时间:2013-07-17 20:13:21

标签: c

编译器没有出现任何错误......它应该是一个基本的电话簿,有5个插槽供人们阅读。出于某种原因,一切似乎都有效,但它不能保存信息。我做错了什么?

typedef struct contact{
  char fname[10];
  char lname[10];
  int pnumber;
};

struct contact p1;
struct contact p2;
struct contact p3;
struct contact p4;
struct contact p5;

int go =0;

int phonebook(struct contact person,int use);

int main(){
 while(go == 0){
   int contact;
   int choice;
   int location;

   printf("first what position in your contacts would you like to change?(1-5)\n");

   scanf("%d",&location);

   printf("what would you like to do?\n1. add a contact\n2. change a contact\n3. print  a 

   contact\n4. Quit\n");

   scanf("%d",&choice);

   switch(location){
    case 1:
     phonebook(p1,choice);
     break;
    case 2:
     phonebook(p2,choice);
     break;
    case 3:
     phonebook(p3,choice);
     break;
    case 4:
     phonebook(p4,choice);
     break;         
    case 5:
     phonebook(p5,choice);
     break;
    default:
     printf("that was not a valid option\n");
  } 
 }

 system("PAUSE");
 return EXIT_SUCCESS;
}

int phonebook(struct contact person,int use){
  switch(use){
   case 1:
    if(person.pnumber>0){ 
      printf("you already have a contact there\n");
    }
    else{
      printf("What is the contact's first name?\n"); 
      scanf("%s", &person.fname);
      printf("\nWhat is the contact's last name?\n");
      scanf("%s", &person.lname);
      printf("\nWhat is the contact's phone number?\n");
      scanf("%d", &person.pnumber);
    }
   break;
  case 2:
   if(person.pnumber == 0)
     printf("No contact is saved in this position\n");
   else{
     printf("What is the contact's first name?\n"); 
     scanf("%s", &person.fname);
     printf("\nWhat is the contact's last name?\n");
     scanf("%s", &person.lname);
     printf("\nWhat is the contact's phone number?\n");
     scanf("%d", &person.pnumber);
   }
  break;     
 case 3:
  printf("\nName:%s\n%s \nNumber:%d \n",&person.fname,&person.lname,&person.pnumber);
  break;
 case 4:
  go = 1;
  break;
 default:
  printf("that wasn't an option. Please pick a valid option next time.\n");
 }

}

2 个答案:

答案 0 :(得分:4)

你有一个简单的问题:C语言使用“按值调用”,因此你的phonebook()函数会获得结构的副本。然后phonebook()函数会更改副本,但更改不会保存在任何位置。

你解决这个问题的方法:你必须让你的phonebook()函数将一个指针带到一个结构中,然后它可以使用指针来修改结构。

int phonebook(struct contact *pcontact, int use)
{
    // ... stuff omitted ...

    printf("What is the contact's first name?\n");
    scanf("%s", pcontact->fname);  // "fname" works as a pointer

    printf("\nWhat is the contact's phone number?\n");
    scanf("%d", &pcontact->pnumber);  // must take address of integer "pnumber"

// ... rest of phonebook() omitted ...

// example of calling phonebook():
case 1:
    phonebook(&p1, choice);

http://www.lysator.liu.se/c/bwk-tutor.html#pointers

答案 1 :(得分:0)

您按值传递person,而不是按引用传递,因此phonebook正在更改联系人结构的副本。

尝试

int phonebook(struct contact *person,int use);