我的问题是,当我运行此函数时,我得到的输出与预期不匹配。我正在尝试打印结构“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/