[英]Unexpected termination of a program in c
我是c的初學者。 今天我遇到了一個問題。 如果我們提供以下輸入,按照書:
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512
輸出將如下所示
And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512
在運行時,它突然終止。
代碼如下:
#include<stdio.h>
#include <ctype.h>
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ;
printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;
}
只需在%c
之前放置空格,所以如果\\n
在緩沖區中,它就不會被讀入。
所以這應該工作:
scanf(" %c %f %d", &b1.name, &b1.price, &b1.pages);
scanf(" %c %f %d", &b2.name, &b2.price, &b2.pages);
scanf(" %c %f %d", &b3.name, &b3.price, &b3.pages);
//^ See the space here, if there is no space but still a '\n' in the buffer it get's read
你的問題是,scanf()在掃描字符串時非常糟糕。 特別是,scanf()無法動態分配(通過malloc())一個字符串,並從輸入中為其分配適當的子字符串。
您的代碼僅解析單個字符: %c
顯而易見的改進 - 在結構中聲明類似char name[40]
東西,然后在掃描代碼中使用%40c
- 也不起作用,因為它不關心字符串結尾。 它將始終消耗您輸入的40個字符,包括數字等。
scanf()的讀取趨勢,直到它得到,它想要什么,也是為什么你的代碼結束為時過早的原因。
因此,通常的解決方案是一次讀取一行輸入(例如,通過fgets()或相當新的庫函數getline()),然后使用您的代碼將該行掃描成適當的部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.