Unexpected program termination in c

I am new to c. I ran into a problem today. According to the book, if we give the 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 will look like this

And this is what you entered 

A  100.000000  354 
C  256.500000  682 
F  233.700000  512 

      

terminates abruptly during its launch.

The code looks like this:

#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 ) ; 
} 

      

+3


source to share


2 answers


Just put spaces in front of it %c

, so if it \n

is in the buffer, it is unreadable.

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 read

      

+6


source


Your problem is that scanf () is horribly broken in regards to line scanning. In particular, scanf () can NOT allocate (via malloc ()) a string on the fly and assign the corresponding substring from the input to it.

Your code only parses one character: %c

The obvious improvement - declaring something like char name[40]

in a struct and then using it %40c

in your scan code - doesn't work either, because it doesn't care about line termination. It will always consume 40 characters from your input, including numbers, etc.



This tendency of scanf () to read until it gets what it wants is also the reason why your codes are ending prematurely.

So the usual solution is to read the input one line at a time (e.g. via fgets () or the rather new library function getline ()) and then use your code to strip that line into appropriate chunks.

+1


source







All Articles