【问题标题】:Data Structures/Records数据结构/记录
【发布时间】:2014-07-07 16:12:01
【问题描述】:

我当前的程序如下所示。这个程序应该询问一个人的 5 条记录并显示它们。

#include<stdio.h>

struct rec {
    char name[100],address[100];
    double age,mobileno;
}x;

main()
{
    int i;
    clrscr();

    for(i=1;i<=5;i++)
    {
        printf("Enter Your Name: ");
        scanf("%s",&x.name);

        printf("Enter Your Age: ");
        scanf("%lf",&x.age);

        printf("Enter Your Address: ");
        scanf("%s",&x.address);

        printf("Enter Your Mobile No.: ");
        scanf("%lf",&x.mobileno);

    }

    printf("\n\nThe Information has been added");
    printf("\n\nNAME        AGE     ADDRESS     MOBILE NUMBER");

    for(i=1;i<=5;i++)
    {
        printf("\n%s        %.0lf       %s      %.0lf",x.name,x.age,x.address,x.mobileno);
    }
    getch();
}

我在显示 5 条不同的记录时遇到问题。如何在一个 printf 中显示 5 条记录?

【问题讨论】:

  • 不要将手机号码存储为双。双打是不精确的,在某些国家还需要前导 0。
  • 您的核心问题是您有一个struct rec 变量x,您试图在其中存储5 个不同的值,并希望以后能够检索所有五个。变量只能存储一个值。你需要了解和使用数组。
  • 我应该使用什么?还是用手机号做?

标签: c data-structures struct


【解决方案1】:

您只需要一组结构来保存数据,目前您只是每次都覆盖数据。有很多方法可以做到这一点,但您可以使用静态数组,例如:

struct rec {
    char name[100],address[100];
    double age,mobileno;
};

int main() {
    struct rec records[5];

    for(i=0;i<5;i++)        // <-- note this is 0 to 4, not 1 to 5
    {
        printf("Enter Your Name: ");
        scanf("%s",records[i].name);  // <-- don't add the & for the string input

printf() 更下方:

for(i=0; i<5; i++)
{
    printf("Name is: %s\n", records[i].name);

【讨论】:

  • 请注意,虽然这个特定的数组大小可能正常工作,但一般来说,将大型结构的大型数组分配为局部变量并不是很好的做法,实际上可能会导致失败有点难以确定原因。在这种情况下,每个 struct rec 大约为 ~220 字节,因此其中 5 个只有 ~1100 字节,但您的堆栈大小有限......
猜你喜欢
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多