I hopelessly tried to copy paste this into another file but it still doesn't return anything.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "conio.h"
#pragma warning (disable: 4996)
typedef struct item
{
char *pName;
int Quantity, Price, Total;
} ITEM;
ITEM *Exam(char *pInput);
int main()
{
ITEM *pItem;
char input[81];
printf("Type items: ");
gets_s(input);
char *pInput = input;
pItem = Exam(pInput);
printf("Name: %s\nQuantity: %d\nPrice: %d\nTotal: %d\n", pItem->pName, pItem->Quantity, pItem->Price, pItem->Total);
free(pItem);
return 0;
}
ITEM *Exam(char *pInput)
{
ITEM *pItem = (ITEM *)malloc(sizeof(ITEM));
char *pNam, *pQuantity, *pPrice;
int total, l, q, p;
int qu, pr;
for (l = 0; *(pInput + l) != ','; l++);
pNam = (char *)malloc(l + 1);
*(pInput + l) = '\0';
strcpy(pNam, pInput);
pItem->pName = pNam;
*(pInput + l) = ',';
for (q = 0; *(pInput + l + 2 + q) != ','; q++);
pQuantity = (char *)malloc(q + 1);
*(pInput + l + q + 2) = 0;
strcpy(pQuantity, pInput + l + 2);
qu = atoi(pQuantity);
pItem->Quantity = qu;
for (p = 0; *(pInput + l + q + 4) != ';' || *(pInput + l + q + 4) != 0; p++);
pPrice = (char *)malloc(p + 1);
*(pInput + l + q + 4) = 0;
strcpy(pPrice, pInput + l + q + 4);
pr = atoi(pPrice);
pItem->Price = pr;
pItem->Total = pr * qu;
return pItem;
}
input is 'shirt, 100, 5'. I want the output to be a structure of name, quantity, price and total. It let me type the input but when i press enter it doesn't return anything. The program just hangs...
The last for in Exam is :
for (p = 0; *(pInput + l + q + 4) != ';' || *(pInput + l + q + 4) != 0; p++);
that for never end because its condition is always true
*(pInput + l + q + 4)
values ';' the test is false || true
then true*(pInput + l + q + 4)
values 0 the test is true || false
then truetrue || true
so again true+ 4
must be + 3
else goes 1 character too farp++
has no effect at all on the testThe test can be changed to !(*(pInput + l + q + 3 + p) == ';' || *(pInput + l + q + 3 + p) == 0)
to stop when ';' or the null character is reached
Of course after *(pInput + l + q + 4) = 0;
must be *(pInput + l + q + 3 + p) = 0;
Note that pQuantity
and pPrice
are allocated but never freed.
Exam can be simplified, for instance :
ITEM *Exam(const char *pInput)
{
ITEM *pItem = (ITEM *)malloc(sizeof(ITEM));
const char *p;
p = strchr(pInput, ',');
pItem->pName = strndup(pInput, p - pInput);
p += 1;
pItem->Quantity = atoi(p);
p = strchr(p, ',') + 1;
pItem->Price = atoi(p);
pItem->Total = pItem->Price * pItem->Quantity;
return pItem;
}
Note that the input string is not modified (I moved it const
) and there is no dynamic allocation except for the result and the name
if you do not have strndup :
char * strndup(const char * s, int n)
{
char * r = (char *) malloc(n + 1);
memcpy(r, s, n);
r[n] = 0;
return r;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments