[英]How to fix my code to read a string in a function that returns a pointer to a struct
我正在編寫一個代碼,它使用 function 返回指向動態分配的結構的指針。 但是,我的代碼沒有讀取字符串。 當我運行它時,它只是跳過“類型名稱”部分,我輸入年齡,它會打印年齡而沒有任何名稱。 奇怪的是,當我使用 scanf 讀取字符串時,代碼可以工作,但它沒有使用 get 或 fgets。 有人可以幫我嗎? 提前致謝。
#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
在輸入 stream 中留下了換行符。 fgets
在調用時將其作為名稱。 為了證明這一點,改變:
scanf("%d", &n);
類似於:
n = 1;
你會發現沒有問題。
如果你不想使用scanf
,你可以調用fgets
然后atoi/strtol
。
char *num;
fgets(num, 100, stdin);
n = atoi(num);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.