簡體   English   中英

為什么我不能輸入第二本書的書名?

[英]why i can't input 2nd book title name?

當我編譯這個程序時,我無法輸入 book2.title 名稱,是使用 get 函數有問題嗎?為什么? 請多解釋一下…………………………………………………………

#include<stdio.h>
#include<string.h>
struct name{
char author[20];
char title[20];
float price;
};
int main()
{
    struct name book1,book2;
    printf("Enter 1st title name:");
    gets(book1.title);
    printf("Enter 1st Author name:");
    gets(book1.author);
    printf("Enter 1st Book price:");
    scanf("%f",&book1.price);
    printf("\nThe 1st Book Name is %s",book1.title);
    printf("\nThe 1st Book Author is %s",book1.author);
    printf("\nThe 1st Book Price is %f",book1.price);
    printf("\nEnter 2nd title name:");
    gets(book2.title);
    printf("Enter 2nd Author name:");
    gets(book2.author);
    printf("Enter 2nd Book price:");
    scanf("%f",&book2.price);

    printf("\nThe 2nd Book Name is %s",book2.title);
    printf("\nThe 2nd Book Author is %s",book2.author);
    printf("\nThe 2nd Book Price is %f",book2.title);
     return 0;


}


您的代碼有兩個與您的問題無關的問題:

  • 獲取的使用
  • printf中的%f用於字符串。

但是,導致您的問題的行為在於以下兩行:

scanf("%f",&book1.price);
...
gets(book2.title);

請注意,當您在終端中輸入 book1 價格(例如 12.3)時,然后按 Enter。 因此, stdin緩沖區保存字符12.3\n scanf 讀取它可以解釋為浮點數的前幾個字節12.3 ,使緩沖區保持\n 現在,當您運行gets ,它會讀取換行符,並且您的第二本書的標題是空白字符串“\0”。

請參閱此網站: https://www.geeksforgeeks.org/problem-with-scanf-when-there-is-fgetsgetsscanf-after-it/

注意:請使用 fgets/scanf/getline 而不是gets。 有關更多信息,請參閱上面評論中@RobertS 發布的鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM