I'm creating a simple program using a structure ItemToPurchase with three data members, char itemName[], int itemPrice, and int itemQuantity. Essentially I need to create two items, item1 and item2, and print out there total cost to the screen. When I used fgets to read into item1.itemName it worked perfectly. My problem is using fgets to get input from the user for item2, it just skips over the read. I'm assuming it's reading a newline or blank space somewhere, but can't figure it out.
Below is my code.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ItemToPurchase.h"
int main()
{
ItemToPurchase item1;
printf("Item 1\n");
printf("Enter the item name:\n");
fgets(item1.itemName, 50, stdin);
printf("Enter the item price:\n");
scanf("%d", &item1.itemPrice);
printf("Enter the item quantity:\n", item1.itemQuantity);
scanf("%d", &item1.itemQuantity);
ItemToPurchase item2;
printf("\nItem 2\n");
printf("Enter the item name:\n");
fgets(item2.itemName, 50, stdin); //this is were i'm getting my bug
printf("Enter the item price:\n");
scanf("%d", &item2.itemPrice);
printf("Enter the item quantity:\n", item2.itemQuantity);
scanf("%d", &item2.itemQuantity);
printf("%s", item1.itemName);
return 0;
}
ItemToPurchase.h
#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H
#endif // ITEMTOPURCHASE_H
#include <stdio.h>
#include <stdlib.h>
typedef struct ItemToPurchase_struct{
char itemName[50];
int itemPrice;
int itemQuantity;
}ItemToPurchase;
void MakeItemBlank(ItemToPurchase* itemToPurchase);
void PrintItemCost(ItemToPurchase price);
ItemToPurchase.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ItemToPurchase.h"
void MakeItemBlank(ItemToPurchase* item){
strcpy((*item).itemName, "none");
(*item).itemPrice = 0;
(*item).itemQuantity = 0;
}
void PrintItemCost(ItemToPurchase item){
printf("%s %d @ $%d = $%d\n", item.itemName, item.itemQuantity, item.itemPrice, item.itemPrice * item.itemQuantity);
}
Output
Item 1
Enter the item name:
cookie
Enter the item price:
12
Enter the item quantity:
13
Item 2
Enter the item name:
Enter the item price:
It doesn't let the user enter any input for item2.itemName. Any help would be appreciated.