I wanted to write an algorithm that takes an input which contains the name of a certain item and its price, and a dash between them. The output is supposed to state the name of the item and its price. I would also like to know how can I separate the input into two strings, one being the name, and the other being the price, since I can't really come up with anything.
int getprice(char item[]);
void printitem(char item[]);
int main()
{
char item[40];
int i, j, len;
int price = 0;
fgets(item, 40, stdin);
price = getprice(item);
printitem(item);
return 0;
}
int getprice(char item[])
{
int i = 0;
int price = 0;
int len = strlen(item);
int temp;
for (i = 0; i < len; i++)
{
if ((item[i] >= '0') && (item[i] <= '9'))
{
break;
}
i++;
}
for (i; i < len; i++)
{
temp = item[i] - '0';
price = price * 10;
price = price + temp;
}
printf("price is: %u\n", price);
return price;
}
void printitem(char item[])
{
int i = 0;
int len = strlen(item);
for (i = 0; i < len; i++)
{
if (item[i] != '-')
{
printf("%c", item[i]);
}
else // if '-' is encountered the next char is checked if it stops or if it needs to keep going
{
i++; //the for loop increments by itself
if (item[i] == ' ') //if there is a space after '-' that means we printed the whole thing
{
break;
}
i--; //if it needs to keep going
printf("-");
}
}
}
Input:Chocolate-Chip Cookie - 30
Output:Item: Chocolate-Chip Cookie
Price: 30
actual Output: Item: Chocolate-Chip Cookie
Price: 262
Why is the output price wrong, and is there a better way of doing it?