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

标签 c struct printf

我的问题是,当我运行此函数时,我得到的输出与预期不匹配。我正在尝试打印结构“Question”的成员,但由于某种原因,成员“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:我已经接受了答案,非常感谢所有有用的评论和努力!

最佳答案

此行为是由于同一缓冲区 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 进行扫描!

关于c - 在 C 中设置 Struct 的字符串成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25718640/

相关文章:

C 中的字符数组(Puts 与 printf)

c - 如何在C中打印缓冲区的内容?

c - 调用函数后如何设置全局数组的大小? (C)

c - 三个不同矩阵的部分的 MPI 用户定义类型

c - 在 C 中,结构体的数据成员如何用作同一结构体的成员所指向的函数的一部分?

c - AVR 上不同内存部分的结构包装

c++ - 如果不在结构中初始化 vector ,它会自动为空还是会具有随机内存位置的值?

C fopen模式参数

c - 返回空结构而不是 NULL 的奇怪问题

java - 将具有多种类型的数组列表与各自的 header 对齐