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 512the output would come like following
And this is what you entered A 100.000000 354 C 256.500000 682 F 233.700000 512while 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 readJust 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更多推荐
发布评论