Indian Currency format is 12345
→ "12,345" (for odd length) and 123456
→ "1,23,456" (for even length). I have included all possibilities such as
- Minus sign: "-12,345"
- Decimal Point: "-12,345.345" or "12,345.123"
- Zero Condition
000000.123
→ "0.123" - Minus and Zero Condition '-000000.123' -> "-0.123"
int main()
{
char currency[20];
char *tmpCurrency=NULL;
int length = 0;
int j = 0, commas = 0,n=0;
int i = 0, cnt = 0;
char *s=NULL;
int signCount=0;
puts("Enter the Currency");
gets_s(currency,20);
n = strspn(currency+1, "0"); //to find number of zeros present in the array.
if (currency[n] == '.' || currency[n]=='\0' ) //for Condtion like 0000000 or 000000.123 so as to maintain one zero so that o/p will be 0 or 0.123
{
memmove(currency, currency + n, strlen(currency));
}
else
{
memmove(currency, currency + n, strlen(currency));
}
signCount==1?currency[0]='-':NULL;
(s = strchr(currency, '.')) ? (length = s - currency) : (length = strlen(currency)); // Considering decimal Point and restricing to Put commas after decimal Point
if (length>3)
commas = (length / 2) - 1; // No of Commas to put
tmpCurrency = (char*)malloc((length + commas+1) * (sizeof(char*)));
while (currency[i] != '\0')
{
if (cnt == commas) //maintaining count to check how many commas have been put in the character array
{
tmpCurrency[j] = currency[i];
i++;
j++;
continue;
}
if (length % 2 == 0) //When length is even comma comes after 1 digit eg 1,23,456. so what i have done adjusting length ann checking when it is becoming even and putting comma.
{
tmpCurrency[j] = currency[i];
if (currency[i] != '-' && currency[i+1]!='.')
{
tmpCurrency[j = j + 1] = ',';
}
i++;
j++;
length = length - 1;
cnt++;
}
if (length % 2 != 0) //for odd length putting one element in tmpCurrency and then subtracting length to make it even.
{
tmpCurrency[j] = currency[i];
i++;
j++;
length = length - 1;
}
}
tmpCurrency[j] = '\0';
strcpy_s(currency,20, tmpCurrency);
puts(currency);
free(tmpCurrency);
return 0;
}
gets_s(currency)
doesn't look right (gets_s
requires 2 arguments). Please double check. \$\endgroup\$