Originally Posted by
whiteflags
A C string is formally defined as a sequence of characters ending with and including zero. If you are going to fill a string backwards you have to take care to do it correctly:
Code:
int next , x;
for (x = len_str - 1 , next = 0; x > -1 && next < len_str; x-- ) {
... determine grouping ...
if (comma) {
buffer[x - next] = ',';
next++;
}
buffer[x - next] = digits[remain];
next++;
... update num ...
if (num == 0) {
buffer[next] = '\0';
break;
}
}
No nudging of x should be necessary; let the loop count backward.
While, in the program you wrote, result will never be negative, it is also impractical to think that always. You'll have to tweak it a bit for that.
Thanks whiteflags.
I have to meditate for a while in order to understand the syntax of your code,
in the meanwhile I came up with a crumpled working solution:
Code:
// ----------------------------------------------------------------------------------------------
// Prog_name: comma_sep.c / ver 0.0
// Date: 27 june 2010
// Author: frktons @ cprogramming forum.
//-----------------------------------------------------------------------------------------------
// A routine for separating integer numbers with thousands comma separator.
// Created with Pelles C for Windows 6.00.4
//-----------------------------------------------------------------------------------------------
#include <stdio.h>
#undef getchar
#pragma comment(lib, "\\masm32\\lib\\msvcrt.lib")
int main(int argc, char *argv[])
{
int num1 = 30000;
int num2 = 50000;
int result = (num1 * num2);
int num = result;
char buffer[14] = {' '};
int len_str = 13;
int x;
int remain = 0;
int count = 0;
char digit[10] = {'0','1','2','3','4','5','6','7','8','9'};
printf("\nThe value of result is: %d\n",result);
for (x = len_str; x > 0; x--)
{
if (num == 0)
break;
if (count == 3)
{
count = 0;
buffer[x] = ',';
x--;
}
remain = num % 10;
num = num / 10;
buffer[x] = digit[remain];
count++;
}
printf("\nThe formatted value of result is: ");
for (x = 0; x < 14; x++)
printf("%c",buffer[x]);
getchar();
return 0;
}
And the output:
Code:
The value of result is: 1500000000
The formatted value of result is: 1,500,000,000
You are totally right about the number being always positive, and I'm
going to complete the logic of the code, as soon as I know how to do it.
This is only a simple exercise I'm doing in order to learn some C syntax, nothing
more for the time being. :-)