在C中设置Struct的字符串成员

时间:2014-09-08 06:39:19

标签: c struct printf

我的问题是,当我运行此函数时,我得到的输出与预期的不匹配。我正在尝试打印结构“问题”的成员,但由于某种原因,成员“text”和“numAnswers”在它们应该不同时是相同的。

int AddQuestion()
{
    Question * question_added;
    Answer * answer_added;
    char input_buf[256];
    unsigned int num_answers;

    fflush(stdin);

    //Create the memory necessary for the new question.
    printf("Add a new question\n");
    question_added = (Question*)malloc(sizeof(Question));

    //Point the head to our new question.
    question_added->pNext = exam.phead; 
    exam.phead = question_added;

    //Get the question text from the user.
    printf("Please enter the question text below:\n");
    if(fgets(input_buf, sizeof(input_buf), stdin))
    {
        question_added->text = input_buf;
    }


    //Get the number of questions from the user
    printf("How many answers are there?:");
    if(fgets(input_buf, sizeof(input_buf), stdin))
    {
        question_added->numAnswers = atoi(input_buf);   
    }


    printf(question_added->text);
    printf("%d\n", question_added->numAnswers);


    return 1;
};

以下是一些示例输出:

MENU:
1. Add a new question.
2. Delete a question.
3. Print the Exam.
4. Quit.
1
Add a new question
Please enter the question text below:
TEST
How many answers are there?:1
1
1

我希望输出为: 测试 1

但两者都给1分。这很令人困惑。在此先感谢您的帮助,了解这里发生了什么。

编辑:包含的结构定义。

typedef struct Question
{
    char* text;
    unsigned int mark;
    Answer** answers;
    unsigned int numAnswers;
    struct Question* pNext;
}Question;

EDIT2:我已经接受了答案,非常感谢所有有用的评论和努力!

2 个答案:

答案 0 :(得分:0)

此行为是由于,缓冲区char input_buf[256];使用了两次。

printf("Please enter the question text below:\n");
if(fgets(input_buf, sizeof(input_buf), stdin)) 
{
    question_added->text = input_buf; // when you enter the string, question_added->text holds its address
}


//Get the number of questions from the user
printf("How many answers are there?:");
if(fgets(input_buf, sizeof(input_buf), stdin)) // but you are using the same buffer here
{
    question_added->numAnswers = atoi(input_buf);   
}

所以input_buf的值被第二个输入替换。那是数字。因此,您获得了2次!

因此,请勿第二次使用input_buf来扫描该号码。使用其他一些使用缓冲区num_answers直接扫描!

答案 1 :(得分:0)

如果您希望答案超出AddQuestion()的范围,您可能希望使用strdup或类似内容(最好是strndup)。这需要您在free成员上致电text。即:

//Get the question text from the user.
printf("Please enter the question text below:\n");
if(fgets(input_buf, sizeof(input_buf), stdin))
{
    question_added->text = strndup(input_buf, sizeof(input_buf));
}


//Get the number of questions from the user
printf("How many answers are there?:");
if(fgets(input_buf, sizeof(input_buf), stdin))
{
    question_added->numAnswers = atoi(input_buf);   
}

然后(在free结构之前):

if (answer->text != NULL) {free(answer->text); answer->text == NULL;}

然后,您始终可以使用input_buf来扫描stdin,并且答案文字超出AddQuestion的范围,我认为这是您想要的。只记得free它!!