gpt4 book ai didi

c - c中的程序意外终止

转载 作者:太空狗 更新时间:2023-10-29 16:01:32 25 4
gpt4 key购买 nike

我是 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

关于c - c中的程序意外终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27448796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com