使用scanf在结构中存储字符串
我已经编写了一个函数,将书籍信息存储到structbook中,除了书名有空格外,其他一切都正常工作。因此,像使用scanf在结构中存储字符串,c,arrays,function,structure,scanf,C,Arrays,Function,Structure,Scanf,我已经编写了一个函数,将书籍信息存储到structbook中,除了书名有空格外,其他一切都正常工作。因此,像Dracula这样的东西会被很好地存储和显示,但像lordoftherings这样的东西只会跳过对本书其余信息的扫描,并继续关闭程序。是否有任何方法可以使用scanf将字符串注册为空格?这是我的密码: void addBook(struct Book book[], int *size) { if(*size== MAX_BOOKS) { p
Dracula
这样的东西会被很好地存储和显示,但像lordoftherings
这样的东西只会跳过对本书其余信息的扫描,并继续关闭程序。是否有任何方法可以使用scanf将字符串注册为空格?这是我的密码:
void addBook(struct Book book[], int *size)
{
if(*size== MAX_BOOKS) {
printf("the inventory is full.\n");
}
else {
printf("ISBN\n");
scanf("%d", &book[*size]._isbn);
printf("Title\n");
scanf("%s", book[*size]._title);
printf("Price\n");
scanf("%f", &book[*size]._price);
printf("Year\n");
scanf("%d", &book[*size]._year);
printf("Qty\n");
scanf("%d", &book[*size]._qty);
printf("Book successfully added to inventory\n");
(*size)++;
}
}
如果需要,我可以使用完整的代码进行更新。没问题。这是因为%s在第一个空格处停止。使用%[^\n]使其读取,直到他找到输入。可能的重复项可以使用
fgets()
或getline()
或scanf(“%[^\n]s”,name)代码>我试过scanf(“%[^\n]s”,书[*size]。\u title)
会完全跳过输入。请尝试以下操作:printf(“Title\n”);getchar();获取(书本[*大小]。\u标题)
所以只要用户不使用enter键进行换行,scanf就会读取每个字符?