2维数组地址簿有fgets问题

时间:2014-08-02 08:35:24

标签: c arrays 2d scanf fgets

这是我的任务:

创建一个程序,允许用户输入最多10个朋友地址。使用二维数组来存储朋友的地址。输入每个地址后,用户应该可以选择输入另一个地址或打印出一个报告,显示到目前为止输入的每个地址。​​

我得到了大部分但我遇到了fgets的主要问题。我一直收到这个错误:

warning: passing arg 1 of `fgets' makes pointer from integer without a cast

代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
    char name[20]= {0};
    char address[40]= {100};
    int choice;
    int i;

    printf("Welcome to the Address Book!\n\n");
    for (i=0;i<10;i++)              //start of the array loop. should give an exit    after each entry
    {
        printf("Would you like to (1)Enter an address, or (2)Print the address book?\n");
        scanf("%i",&choice);
        switch (choice)
        {
            case 1:
            {
                printf("Please enter a name...\n");
                fgets(name[i],20,stdin);
                printf("You entered %s .", name);
                printf("Please enter an address...\n");
                fgets(address[i],40,stdin);
                printf("You enteres %s .", address);
            }
                break;
            case 2:
                for (i = 0; i<10; i ++)
                {
                    printf("%s\n", name[i]);
                    printf("%s\n", address[i]);
                }
                break;
        }
    }
    return (0);
}

1 个答案:

答案 0 :(得分:1)

在下面找到更正后的代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
    char name[10][20]; //Fix3
    char address[10][40];//Fix4
    int choice;
    int i, j;

    printf("Welcome to the Address Book!\n\n");
    for (i=0;i<10;i++)              //start of the array loop. should give an exit    after each entry
    {
        printf("Would you like to (1)Enter an address, or (2)Print the address book?\n");
        scanf("%i",&choice);
        switch (choice)
        {
            case 1:
            {
                printf("Please enter a name...\n");
                getchar(); //Fix1
                fgets(name[i],20,stdin); 

                printf("You entered %s .", name);
                printf("Please enter an address...\n");
                //getchar();//Fix2

                fgets(address[i],40,stdin);
                printf("You enteres %s .", address);
            }
                break;
            case 2:
            {
                for (j = 0; j<i; j ++)
                {
                    printf("%s\n", name[j]);
                    printf("%s\n", address[j]);
                }
              }
                break;
        }
    }
    return (0);
}

更正是:

  1. 2D数组用于获取名称和地址
  2. getchar()被调用以消费&#39; \ n&#39;在使用fgets();
  3. 之前