C中的scanf字符串和printf无法按预期工作

时间:2014-11-24 22:03:50

标签: c string printf scanf

我正在为我的大学计算机科学课程练习。

我必须使用多个scanf和printf来获取有关书籍的数据,数据存储在结构中。

要求数据的功能是

book_t addbook() {
    book_t book;

    printf("Insert ISBN: ");
    scanf("%s", book.isbn);

    printf("Insert author: ");
    scanf("%s", book.author);

    printf("Insert title: ");
    scanf("%s", book.title);

    printf("Insert year: ");
    scanf("%d", &book.year);

    printf("Insert shelf: ");
    scanf("%d", &book.shelf);

    printf("Insert price: ");
    scanf("%lf", &book.price);

    return book;
}

但是当我运行程序时,在控制台上我得到了这个:

Insert ISBN: 978-88-08-06485-1
Insert author: Author Name
Insert title: Insert year:

我写了ISBN并按下了返回,我写了作者姓名并按下了返回,我得到了下两个printf,这怎么可能?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

可能在您提供作者姓名时,您提供了其全名(第一个+姓氏)。 C仅将作者名称解析为名字,并且由于缓冲区有另一个字符串,因此它被用作标题名称,因此不会要求您提供另一个字符串。

下面是一个复制品:

enter image description here

在这个例子中,作者被设置为" Jon"标题设置为Doe:

enter image description here

答案 1 :(得分:0)

scanf读取,直到找到空格字符。在你的情况下:

ISBN: blabla -> scanf reads blabla
Author: Author Name -> scanf reads Author
title: -> scanf has already Name in buffer, so Name is set into title immediatly
year: -> input next.

因此,跳过了标题的输入,因为scanf已经有一个缓冲值

相关问题