Let me start by saying I appreciate your first post here.
- You mentioned that you've searched for answers
- You read the rules
- You cut your program down into a simplified example that demonstrated the problem
- You clearly asked your question
- You used code tags
- You used decent indentation in the code
So just for that, I'd like to say thanks!
You were given the wisdom in post #8 about how "simple it is to parse well formatted input using a combination of fgets() and sscanf()."
Based on the input you provided, your input is well formatted - but notice how it's different based on two possible scenarios.
Code:
Daniel paid $78 for each of 2 coats.
[Name] ... [Cost] ... ... ... [Quantity] [Item]
Kemal bought 3 shirts for $19 each.
[Name] ... [Quantity] [Item] ... [Cost] ...
You need to take these two possible scenarios into account. The "scanf()" family returns the number of items successfully read. So you can scan each string checking to see if it took all the arguments for the first scenario - if not, re-scan it while checking to see if it took all the arguments for the second scenario. If the input you provided is consistent, then any deviation from these two scenarios can be considered an error.
Here is an example for you to study. Note how the return value of "sscanf()" is used, and how you can ignore unwanted input with the '*' symbol within the format specifiers (read more here):
Code:
#include <stdio.h>
#define MAX_ELEMENTS 6
#define MAX_STR_LEN 256
const char *input[MAX_ELEMENTS] =
{
"Daniel paid $78 for each of 2 coats.",
"Daniel paid $97 for each of 5 books.",
"Kemal bought 3 shirts for $19 each.",
"Daniel paid $89 for each of 4 coats.",
"Daniel bought 2 coats for $95 each.",
"Tristyn paid $43 for each of 3 meals."
};
int main(void)
{
char name[MAX_ELEMENTS][MAX_STR_LEN];
int cost[MAX_ELEMENTS];
int quantity[MAX_ELEMENTS];
char item[MAX_ELEMENTS][MAX_STR_LEN];
int i;
for(i=0; i<MAX_ELEMENTS; i++)
{
/* fgets() the string */
if(sscanf(input[i],"%s %*s %*c %d %*s %*s %*s %d %s",name[i],&cost[i],&quantity[i],item[i]) != 4)
if(sscanf(input[i],"%s %*s %d %s %*s %*c %d %*s",name[i],&quantity[i],item[i],&cost[i]) != 4)
printf("\n Bad formatting!\n");
}
for(i=0; i<MAX_ELEMENTS; i++)
printf("Name: %s\nCost: %d\nQuan: %d\nItem: %s\n\n",name[i],cost[i],quantity[i],item[i]);
return 0;
}