每次我尝试使用结构体数组并从用户那里获取输入时,都会跳过scanf,但我不知道为什么。 我通过仅使1个元素组成的数组并仅针对该元素而不是for循环进行扫描来简化了代码,但是它仍然无法正常工作。
#include <stdio.h>
#include <string.h>
int main(){
typedef struct {
char title[30];
char author[30];
int year;
} Books;
Books library[1]; //array of structs
//input
printf("\nAdd a new book to the shelf");
printf("\nTitle: ");
scanf("%[^\n]",library[0].title);
printf("\nAuthor: ");
scanf("%[^\n]",library[0].author);
printf("\nYear: ");
scanf("%d",&library[0].year);
//print
printf("\nTitle: ");
printf("%s",library[0].title);
printf("\nAuthor: ");
printf("%s",library[0].author);
printf("\nYear: ");
printf("%d\n",library[0].year);
return 0;
}
终端:
Add a new book to the shelf
Title: Fist Book //input by user
Author: //doesn't let me scan anything and jumps to Year:
Year: 1998 //input
Title: Fist Book
Author:
Year: 1998
答案 0 :(得分:2)
在scanf
中,%[^\n]
不会跳过空格。要跳过空格(应该可以解决您的问题),请执行以下操作:
scanf(" %[^\n]", library[num].member);