使用scanf在结构中存储字符串

时间:2017-04-01 20:32:30

标签: c arrays function structure scanf

我已经编写了一个函数,可以将书籍上的信息存储到struct Book中,除了书名中有任何空格外,一切正常。因此Dracula之类的内容会被存储和显示得很好,但像Lord of the Rings这样的内容只会跳过扫描本书其余部分的信息并继续关闭程序。有没有办法使用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)++;
                }

}

如有必要,我可以使用完整代码进行更新。

1 个答案:

答案 0 :(得分:1)

没问题。那是因为%s停在第一个空间。使用%[^ \ n],直到找到输入为止。