如何修复我的代码以读取函数中的字符串,该函数返回指向结构的指针 [英] How to fix my code to read a string in a function that returns a pointer to a struct
问题描述
我正在编写一个代码,该代码使用一个函数来返回指向结构的指针,该结构是动态分配的.但是,我的代码没有读取字符串.当我运行它时,它只跳了类型名称"部分,键入了年龄,并且它显示了年龄,并且没有显示任何名称..............................................................................................奇怪的是,当我使用scanf读取字符串时,该代码有效,但gets或fgets却没有.谁能帮我吗?预先感谢.
I'm writing a code that uses a function to return a pointer to a struct, which is allocated dynamically. However, my code isn't reading strings. When I run it, it simply jumps the "Type name" part, I type the age, and it prints the age and nothing for the name. Strangely, the code works when I use scanf to read the string, but it didn't with gets or fgets. Could anyone please help me? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
struct details
{
char name[100];
int age;
};
struct details * details_pointer(int n)
{
struct details *pointer = (struct details *) malloc (n*sizeof(struct details));
for (int i=0; i<n; i++)
{
printf("Student %d:\n", i);
printf("name:\n");
scanf("%s", pointer[i].name);
//gets(pointer[i].name); not working
//fgets(pointer[i].name, 100, stdin); not working
printf("age:\n");
scanf("%d", &pointer[i]. age);
}
return pointer;
}
int main()
{
int n;
printf("Type the number of persons:\n");
scanf("%d", &n);
struct details *student = details_pointer(n);
for (int i=0; i<n; i++)
{
printf("\nName: %s", (*(student+i)).name);
printf("Age: %d\n", (*(student+i)).age);
}
free(student);
system("pause");
return 0;
}
推荐答案
这是因为scanf
在输入流中留下了换行符. fgets
在调用它时将其作为名称.为了证明这一点,请更改:
This is because scanf
leaves a newline in the input stream. fgets
gets it as the name when it is called. To prove this, change:
scanf("%d", &n);
类似于:
n = 1;
您将看不到任何问题.
如果您不想使用scanf
,则可以先呼叫fgets
,然后再呼叫atoi/strtol
.
If you don't want to use scanf
, you can call fgets
then atoi/strtol
.
char *num;
fgets(num, 100, stdin);
n = atoi(num);
这篇关于如何修复我的代码以读取函数中的字符串,该函数返回指向结构的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!