当输入一个名字,例如 阿尔法-贝塔,我似乎无法让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?
Scanf()只扫描非空格。如果要获得空格,你可以使用fgets()。
fgets(&ptr->name, 20, stdin)
20是任意的。选择你所需要的字符数,以供参考。https:/docs.microsoft.comen-uscppc-runtime-libraryreferencefgets-fgetws?view=vs-2019。
试试这个。
#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