C语言程序意外终止

3

我是一个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 ) ; 
} 

4
你有什么问题? - dg99
问题是我无法将以下内容作为输入提供给我的代码:A 100.000 354 C 256.5 682 C 233.7 512。 - Deepak Kumar
1
主函数应该是int main(void),并以return 0;结尾。 - abelenky
我也尝试过那个。 - Deepak Kumar
2个回答

6
只需在% 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

1
你的问题是scanf()在扫描字符串方面非常糟糕。特别是,scanf()不能通过malloc()动态分配一个字符串,并将适当的子字符串赋值给它。
你的代码只解析单个字符:%c
显而易见的改进方法——在结构体中声明类似char name[40]这样的变量,然后在扫描代码中使用%40c——也行不通,因为它不关心字符串结束符。它总是从输入中读取40个字符,包括数字等。
scanf()读到它想要的东西就停止的倾向也是你的代码过早结束的原因。
因此,通常的解决方法是一次读取一行输入(例如,通过fgets()或相对较新的库函数getline()),然后使用你的代码将该行划分为适当的部分。

1
抱歉,目标是输入一个字符而不是一个字符串。那么为什么要浪费内存呢? - Deepak Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接