I'm making a program which asks the user to type a list of 5 products and their price. Both the names and the prices are stored in two parallel arrays which will be later be used together to output the price of each product. The function used to ask for input and store the information is the following:
void NamesAndPrices(char products[5][41], float prices[5]) {
for (int i = 0; i < 5; i++) {
printf("Type the name of the product: ");
fgets(products[i], 41, stdin);
strtok(products[i], "\n");
printf("Type the price: ");
scanf("%f", &prices[i]);
}
}
It receives two arguments: the arrays where the information will be stored, both declared in the main()
function:
int main() {
char products[5][41];
float prices[5];
NamesAndPrices(products, prices);
return 0;
}
When the code is compiled and run, it asks for the name of the product only once. Here's an example:
Type the name of the product: 40 x 60 Rug
Type the price: 39.99
Type the name of the product: Type the price: 0
Type the name of the product: Type the price: 0
Type the name of the product: Type the price: 0
Type the name of the product: Type the price: 0
Why is fgets()
ignored after the first execution of the statements?