Piyush Malviya Piyush Malviya - 9 months ago 29
C Question

Why runtime error occurs on using character element in array of structures

I am using Codeblocks IDE with GCC compiler.

I am trying to implement the array of structures with different types of elements in a structure.
Till now, every array of structure works fine. but when I use character type of variable as a structure element then I get a runtime error.
why does this happen ?
The code is :

#include <stdio.h>
int main( )
struct book
char name ;
float price ;
int pages ;
} ;
struct book b[3] ;
int i ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "\nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
return 0;



The problem is that %c is not just for reading visible characters, it will read any character, including control characters.

If your input looks like this:

a 1.23 5
b 2.34 10
c 10.98 7

The first line will read a into book[0].name, 1.23 into book[0].price, and 5 into book[0].pages. So reading the first line works correctly.

At this point, the next character in the input is the newline character at the end of the first line. So when you perform the next scanf, it will read \n into book[1].name. Then it tries to read b into book[1].price, but it fails because this isn't a valid floating point number.

The solution is to put a space before %c in the format string. This tells scanf to skip over any whitespace characters before trying to read something with the %c format. So it will skip over the newlines, and put the first visible character into books[i].name.

    scanf ( " %c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;