在C语言中,当使用结构指针时,不能得到空格后的字。

问题描述 投票:0回答:1

当输入一个名字,例如 阿尔法-贝塔,我似乎无法让scanf读取空白处("贝塔")后面的单词... ...

#include<stdio.h>

struct student
{
 int rollno, class; 
 char name[50], div[10];
};

int main()
{
struct student s1, *ptr;
ptr = &s1;
printf("\nEnter Student Class: ");
scanf("%d",&ptr->class);
printf("\nEnter Student Division: ");
scanf("%s",&ptr->div);
printf("\nEnter Student Rollno: ");
scanf("%d",&ptr->rollno);
printf("\nEnter Student Name: ");
scanf("%49s",&ptr->name);

printf("\nClass: %d\n", ptr->class);
printf("\nDivision: %s\n", ptr->div);
printf("\nRollno: %d\n", ptr->rollno);
printf("\nName: %s\n", ptr->name);
return 0;
}

当打印名称时,它只返回 "Alpha",而不是 "Alpha Beta",我应该怎么做才能让它同时读取Alpha和Beta?

c pointers structure
1个回答
0
投票

Scanf()只扫描非空格。如果要获得空格,你可以使用fgets()。

fgets(&ptr->name, 20, stdin)

20是任意的。选择你所需要的字符数,以供参考。https:/docs.microsoft.comen-uscppc-runtime-libraryreferencefgets-fgetws?view=vs-2019。


0
投票

试试这个。

#include<stdio.h>

struct student
{
 int rollno, class; 
 char name[50], div[10];
};

int main()
{
struct student s1, *ptr;
ptr = &s1;

printf("\nEnter Student Class: ");
scanf("%d",&ptr->class);
printf("\nEnter Student Division: ");
scanf("%s",ptr->div);
printf("\nEnter Student Rollno: ");
scanf("%d",&ptr->rollno);
printf("\nEnter Student Name: ");
scanf(" %50[A-Za-z ]",ptr->name);

printf("\nClass: %d\n", ptr->class);
printf("\nDivision: %s\n", ptr->div);
printf("\nRollno: %d\n", ptr->rollno);
printf("\nName: %s\n", ptr->name);

return 0;
}

执行。

./student

Enter Student Class: 1

Enter Student Division: 2

Enter Student Rollno: 3

Enter Student Name: Alpha Beta

Class: 1

Division: 2

Rollno: 3

Name: Alpha Beta
© www.soinside.com 2019 - 2024. All rights reserved.