如何在数组中使用int?

时间:2013-10-06 02:59:25

标签: c arrays struct int

我创建了一个非常简单的编码,它没有错误,但是当它运行时,我不能把输入放在'年龄'一边。

#include <stdio.h>
#include <conio.h>


struct baby
{
    char name[2][30];
    char sex[2][7];
    char birthday[2][12];
};

struct parents
{
    char nama[2][30];
    int age[2];
};

struct momdad
{
    struct parents father;
    struct parents mother;
};

struct momdad info;
struct baby newborn;

int main()
{
    int i;

    for(i=0;i<2;i++)
    {
        printf("\nEnter baby's name %d: ",i+1);
        gets(newborn.name[i]);

        printf("Enter baby's sex %d (Female/Male): ",i+1);
        gets(newborn.sex[i]);

        printf("Enter baby's birthday %d (dd/mm/yyyy): ",i+1);
        gets(newborn.birthday[i]);

        printf("Enter father's name %d: ",i+1);
        gets(info.father.nama[i]);
        printf("Enter father's age %d: ",i+1);
        gets(info.father.age[i]);

        printf("Enter mother's name %d: ",i+1);
        gets(info.mother.nama[i]);
        printf("Enter mother's age %d: ",i+1);
        gets(info.mother.age[i]);



    }

    printf("\n\n\tNEW BORN BABY IN KUANTAN HOSPITAL");
    printf("\n\n===============================================");

    for(i=0;i<2;i++)
 {


        printf("\n\nBaby name: %s",newborn.name[i]);
        printf("\nSex: %s",newborn.sex[i]);
        printf("\nBirthday: %s",newborn.birthday[i]);
        printf("\n\nFather name: %s",info.father.nama[i]);
        printf("\nFather age: %s",info.father.age[i]);
        printf("\n\nMother name: %s",info.mother.nama[i]);
        printf("\nMother age: %s",info.mother.age[i]);
        printf("\n\n----------------------------------------------");
 }

    getch();
}

这是我的声明,我认为是错的,但我不知道如何。

int age[2];

并且输入将放在这里

printf("Enter father's age %d: ",i+1);
gets(info.father.age[i]);

n在这里

printf("Enter mother's age %d: ",i+1);
gets(info.mother.age[i]);

我仍然是编程的新手抱歉提出这个简单的问题

1 个答案:

答案 0 :(得分:0)

永远不要使用gets()。它无法安全使用,截至2011年已从语言中删除。

在评论中,您提到调用fflush(stdin);fflush的行为未定义输入流。一些实现定义了行为,但取决于它会使您的程序不可移植 - 而且无论如何您都不需要它。

读取输入数据的最简单方法是使用scanf(),但这有一些问题。例如,如果您使用scanf("%d", &n);并输入123,它将使用123并在其后面留下任何内容(例如换行符)等待阅读。

读取输入的更好方法是使用fgets读取一行文本,然后使用sscanf来解析输入行中的数据。它重新

以下是一个例子:

#define MAX_LEN 200
char line[MAX_LEN];
int num;

printf("Enter an integer: ");
fflush(stdout);

if (fgets(line, MAX_LEN, stdin) == NULL) {
    fprintf(stderr, "Error reading line\n");
    exit(EXIT_FAILURE);
}
if (sscanf(line, "%d", &num) != 1) {
    fprintf(stderr, "Error parsing integer from line\n");
    exit(EXIT_FAILURE);
}
printf("The number is %d\n", num);

我在第一个fflush(stdout)之后调用printf以确保提示实际出现。 stdout可以是行缓冲的,这意味着在您打印整行之前不会显示输出。 fflush并不总是必要的,但这是一个好主意。

fgets调用会读取输入 MAX_LEN字符的完整行,如果该行长于此字符。 (gets无法指定最大输入大小,因此无论目标数组有多大,它都可以读取更多内容并使用clobber随机内存。)fgets返回空指针(如果有)问题,我检查一下。

sscanfscanf类似,但它从内存中的字符串中读取数据,而不是从标准输入中读取数据。 (还有fscanf,它从指定的文件中读取。)它返回成功扫描的项目数,因此1以外的值表示错误。

我建议阅读所有这些功能的文档;我没有涵盖他们所做的一切。实际上,您应该阅读您使用的任何标准库函数的文档。

相关问题