1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#if HAVE_CONFIG_H
# include "config.h"
#endif
#if ! defined(HAVE_CONFIG_H) || HAVE_STRING_H
# include <string.h>
#endif
#include <stdlib.h> /* for calloc() */
#include <ctype.h>
#include "calculator.h"
#include "add_commas.h"
#ifdef MEMWATCH
#include "memwatch.h"
#endif
/* this function returns a copy of the input string with delimiters
* appropriate for the specified base. */
char *add_commas(char *input, int base)
{
char *copyto, *copyfrom, *tmpstring, *delimiter;
unsigned int skip, prefix;
unsigned char ctr;
char separator;
char dec_delim = conf.dec_delimiter;
size_t preflen;
Dprintf("add_commas: %s, %i\n", input, base);
if (NULL == input) {
return NULL;
}
if (!isdigit(*input)) {
return NULL;
}
delimiter = strchr(input, dec_delim);
if (NULL == delimiter) {
dec_delim = 0;
delimiter = strrchr(input, 0);
}
Dprintf("add_commas: input: %s\n", input);
switch (base) {
default:
case DECIMAL_FORMAT:
skip = 3;
prefix = 0;
separator = conf.thou_delimiter;
break;
case HEXADECIMAL_FORMAT:
skip = 2;
prefix = 2;
separator = ' ';
break;
case OCTAL_FORMAT:
skip = 4;
prefix = 1;
separator = conf.thou_delimiter;
break;
case BINARY_FORMAT:
skip = 8;
prefix = 2;
separator = conf.thou_delimiter;
break;
}
if (!conf.print_prefixes) {
prefix = 0;
}
if (*input == '-') {
prefix++;
}
// the meat of the function
preflen = delimiter - input;
if (preflen < (skip + prefix)) {
return NULL;
}
Dprintf("tmpstring is alloc'd to be %lu long\n", preflen + strlen(input));
tmpstring = calloc(preflen + strlen(input), sizeof(char));
ctr = (delimiter - (input + prefix)) % skip;
if (ctr == 0) {
ctr = skip;
}
copyfrom = input;
copyto = tmpstring;
while (*copyfrom && *copyfrom != dec_delim && *copyfrom != 'E' && *copyfrom != 'e') {
Dprintf("from: %s to: %s \n", copyfrom, tmpstring);
*copyto++ = *copyfrom++;
if (prefix != 0) {
prefix--;
continue;
}
if (--ctr == 0) {
*copyto++ = separator;
}
if (ctr == 0) {
ctr = skip;
}
}
Dprintf("*(copyto - 1) == %c\n",*(copyto-1));
Dprintf("*(copyfrom - 1) == %c\n",*(copyfrom-1));
if (*(copyto - 1) == separator) {
*(copyto - 1) = dec_delim;
}
if (*copyfrom == 'e' || *copyfrom == 'E') {
*copyto++ = *copyfrom;
}
if (*copyfrom) {
copyfrom++;
while (*copyfrom) {
*copyto++ = *copyfrom++;
}
}
return tmpstring;
}
|