c - 二维数组地址簿存在 fgets 问题

标签 c arrays 2d scanf fgets

这是我的作业:

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

我明白了大部分内容,但我遇到了 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);
}

最佳答案

在下面找到更正的代码

#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. 二维数组用于获取姓名和地址
  2. 在使用fgets()之前调用getchar()来消耗'\n';

关于c - 二维数组地址簿存在 fgets 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25093210/

相关文章:

c - C 中正确的 typedef 语法

使用 numpy 数组输入的 Python 函数给出意外结果

c - 点在直线上特定距离 C

c# - 使用字符串拆分方法时设置数组的大小

ios - 如何在iOS上绘制二维正方形矩阵?

c - 释放二维数组 - 检测到堆损坏

c - 错误 : #29: expected an expression in C

c - 文件中此时函数 ' ' 的参数过多

c - 如何合并排序字符?

arrays - 在 Fortran 90 中编写动态数组