c中的程序意外终止(Unexpected termination of a program in c)

编程入门 行业动态 更新时间:2024-10-11 23:17:46
c中的程序意外终止(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 ) ; }

I am beginner in c . Today i faced a problem . As per book if we give following input :

Enter names, prices and no. of pages of 3 books A 100.00 354 C 256.50 682 F 233.70 512

the output would come like following

And this is what you entered A 100.000000 354 C 256.500000 682 F 233.700000 512

while on running it terminates abruptly .

The code is as follows:

#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

Just put spaces before %c so if a \n is in the buffer it doesn't get read in.

So this should work:

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

更多推荐

本文发布于:2023-04-29 07:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335635.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   程序   Unexpected   termination   program

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!