Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have the following code

for(int i=0;i<n;i++){
				fgetc(stdin);
				printf("\n\n");
				printf("Please enter the item %d\t", i+1);
				fgets(ord.itm[i].item,50,stdin);
				ord.itm[i].item[strlen(ord.itm[i].item)-1]=0;
				 printf("\nPlease enter the quantity:\t");
				 scanf("%d",&ord.itm[i].qty);
				 printf("\nPlease enter the unit price:\t");
				 scanf("%f",&ord.itm[i].price);


What I have tried:

i think fgetc removed enter from scan command but why doesn't it happen with the loop after replacing it with %.2f
Posted
Updated 20-Dec-22 7:13am

In addition to watch Richard wrote, scanf can be a problematic function. You are already calling fgets and it is better function to use for acquiring input. You can convert strings to numeric values with atoi[^] and atof[^]. You can also easily adapt your code to read input from a file instead of stdin if you want to and that can make your testing go much faster and easier. You can do that be first calling fopen[^] to open the file. This documentation for fgets[^] has a snippet of code that opens a text file and reads lines of text from it. If you add the for loop you already have and its code then you are ready to go.
 
Share this answer
 
You cannot use a precision size for an input field like that, it only has meaning when displaying the value. See Format specification fields: scanf and wscanf functions | Microsoft Learn[^] for complete details.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900