This code is not running. i'm using gcc

#include<stdio.h>
int main()
{
	struct book
	{
		char name[10];
		float price;
		int pages;
	};

	struct book b[5];
	int i;

	for (i=0; i<5; i++)
	{
		printf("Enter name, price and pages\n");
		scanf("%c %f %d", &b[i].name, &b[i].price, &b[i].pages);
	}

	for (i=0; i<5; i++)
		printf("%c %f %d\n", b[i].name, b[i].price, b[i].pages);

	return 0;
}

Recommended Answers

All 5 Replies

IN line 17, the '%c' should be replaced by '%s' since name is a string(an array of characters) not a single char.
Same thing in line 21 while using printf.
Despite the above changes alot could go wrong with your program. Try using fgets() instead of scanf while taking strings as input.
I just entered "Ban ki Moon" for the 'name' part and your program fell apart.

In line number 17 and 21 %c is replaced as %s......

Despite the above changes alot could go wrong with your program. Try using fgets() instead of scanf while taking strings as input.
I just entered "Ban ki Moon" for the 'name' part and your program fell apart.

Still isn't working

#include<stdio.h>
#include<string.h>
int main()
{
	struct book
	{
		char name[25];
		float price;
		int pages;
	};

	struct book b[5];
	int i;

	for (i=0; i<5; i++)
	{
		printf("Enter name, price and pages\n");
		fgets(b[i].name, 25, stdin);
		scanf("%f %d", &b[i].price, &b[i].pages);
	}

	for (i=0; i<5; i++)
	{
		printf("%s %f %d\n", b[i].name, b[i].price, b[i].pages);
	}

	return 0;
}

You might want to add a getchar() after that scanf ,

...
printf("Enter name, price and pages\n");
fgets(b[i].name, 25, stdin);
scanf("%f %d", &b[i].price, &b[i].pages);
getchar();
}
...

After scanf has read your input ,a '\n'(which was typed just after the number) is still left in the input buffer, so we use that getchar to empty the buffer.
scanf() is a bit complex function to handle, especially when taking input interactively from the user. It'll fail to do the job at hand if it doesn't get what it is expecting.Here in your program, user must enter a string followed by a floating point number followed by an integer.If a user fumbled and mistakenly (or intentionally) entered a floating point number instead of an integer, the program will misbehave.
So I'd suggest you to use fgets even also to read the numbers the from user and later convert them using atoi and atof to their respective formats.

thanks for the help diwakar :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.