C++ Formatting Numbers to Strings


 
Thread Tools Search this Thread
Top Forums Programming C++ Formatting Numbers to Strings
# 1  
Old 10-06-2010
C++ Formatting Numbers to Strings

Hi All,

Sorry to say I have 0 experience writing C++ but have been asked to write a piece of code that will take a double input and an integer for number of decimal places as well as integer for padding and output a string that represents the double formatted (with comma thousand separators - could be parameterised too, not necessary for now).

eg.

Code:
formatNum(1123.45,3,8) = "   1,123.450"
formatNum(1123.45,2,8) = "   1,123.45"
formatNum(1123.45,1,8) = "   1,123.4" (truncation rather than rounding)

The padding should actually align the decimal points (or lack thereof) eg

Code:
                   1
                   1.10
                   1.11
                 111.11
               1,111
           1,111,111.10

The code I have so far is (admittedly probably useless):

Code:
#include <stdlib.h>
#include <stdio.h>
char *formatNum(double num, int dec, int pad)
{
  char* OutStr;
  sprintf(OutStr,"%f",num);
  return OutStr;
}

Help would be highly appreciated as always!

Lee

Last edited by Scott; 10-06-2010 at 01:54 PM.. Reason: More code tags
# 2  
Old 10-06-2010
sprintf expects a pointer to a buffer, not a pointer to nothing, so that's wrong.

You can't return a pointer to a local variable either, so that's also wrong. C strings are pointers, not objects, you can't expect them to allocate themselves. You should probably pass memory into the function for it to use.

You could start like this:

Code:
#include <stdio.h>
#include <string.h>

void formatNum(char *buf, double n, int decimals, int pad)
{
        char cmdstr[64]; // Holds a command string for sprintf
        sprintf(cmdstr, "%%.%df", decimals); // Create a format string like %.3f
        memset(buf, ' ', pad); // Fill padding area with spaces
        sprintf(buf+pad, cmdstr, n);        // Print after spaces
}

int main(void)
{
        char buf[128]; // sprintf needs a buffer, not just a pointer.
        formatNum(buf, 3.14159, 3, 8);
        printf("Result was:  '%s'\n", buf);
}

You'll need to add the thousand seperators yourself, printf can't do it reliably, and chop off extra whitespace from the front after sprintf is called, probably with memmove().
# 3  
Old 10-15-2010
Partial Solution

Hi,

We decided to go for a different option in the end (being untrained and useless in C++).

Thanks for the advice Corona, here's the partial solution I had when we called it off in case it helps anyone else. Apologies again if it's poor coding practice/style.

Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void subString(const char *source, int begin, int end, char *destination) {
 int i = 0;
 while ( begin <= end ) {
  destination[i++] = source[begin++];
 }
}
char *commaInt(unsigned long n)
{
 static int comma = ',';
 static char retbuf[30];
 char *p = &retbuf[sizeof(retbuf)-1];
 int i = 0;
 *p = '\0';
 do {
  if(i%3 == 0 && i != 0)
  *--p = comma;
  *--p = '0' + n % 10;
  n /= 10;
  i++;
 } while(n != 0);
 return p;
}
char *commaStr(char* inStr, int decimals, int padto)
{
 double inDbl = atof(inStr);
 
 char cmdstr[64];
 static char retbuf[256];
 char *out = &retbuf[sizeof(retbuf)-1];
 long intpart = (long)inDbl;
 char* front = commaInt(intpart);
 char* intpartStr;
 sprintf(intpartStr,"%ld",intpart);
 int intpartLen = strlen(intpartStr);
 char decSubstr[80];
 memset(decSubstr, 0L, sizeof(decSubstr));
 subString(inStr, intpartLen, intpartLen + decimals, decSubstr);
 printf("DecSubstr: %s\n", decSubstr);
 sprintf(cmdstr, "%%%ds%%s\n", padto, decimals); // Create a format string like %10s%s
 sprintf(retbuf, cmdstr, front, decSubstr);
 
 out=retbuf;
 return out;
}
int main() {
 char* inStr;
 char* fmtStr;
 inStr = "923456712345678.1234";
 fmtStr = commaStr(inStr,3,25);
 printf("Formatted: %s", fmtStr);
 inStr = "456712345678.123456";
 fmtStr = commaStr(inStr,3,25);
 printf("Formatted: %s", fmtStr);
 inStr = "923456712345678.1";
 fmtStr = commaStr(inStr,3,25);
 printf("Formatted: %s", fmtStr);
 inStr = "923456712345678.1";
 fmtStr = commaStr(inStr,1,25);
 printf("Formatted: %s", fmtStr);
}

Cheers,

Lee
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

How to pass strings from a list of strings from another file and create multiple files?

Hello Everyone , Iam a newbie to shell programming and iam reaching out if anyone can help in this :- I have two files 1) Insert.txt 2) partition_list.txt insert.txt looks like this :- insert into emp1 partition (partition_name) (a1, b2, c4, s6, d8) select a1, b2, c4, (2 Replies)
Discussion started by: nubie2linux
2 Replies

2. Shell Programming and Scripting

Sort strings containing numbers

How can I sort this, first by 2nd field then by 1st field. tried sort -b -k 2,2 Input: AS11 AB1 BD34 AB10 AF12 AC2 A345 AB10 R134 AB2 456 AC10 TTT2 BD12 desired output: AS11 AB1 R134 AB2 A345 AB10 BD34 AB10 AF12 AC2 456 AC10 TTT2 BD12 (2 Replies)
Discussion started by: aydj
2 Replies

3. Shell Programming and Scripting

Sort strings with numbers

I want to sort my data first by the 2nd field then by the first field. I can't use sort -V because I don't have gnu sort and cannot install one. How do I go about this? Input: G456 KT1 34 K234 KT10 45 L2 KT2 26 H5 LAF2 28 F3 LAF2 36 Output: G456 KT1 34 L2 KT2 26 K234 KT10 45 F3... (14 Replies)
Discussion started by: aydj
14 Replies

4. Shell Programming and Scripting

Trying to take file numbers from a file, pass them to sed to change strings in corresponding lines

I have a bunch of file numbers in the file 'test': I'm trying the above command to change all the instances of "H" to "Na+" in the file testsds.pdb at the line numbers indicated in the file 'test'. I've tried the following and various similar alternatives but nothing is working: cat test |... (3 Replies)
Discussion started by: crunchgargoyle
3 Replies

5. Shell Programming and Scripting

Replace a multi-line strings or numbers

Hi I have no experience in Unix so any help would be appreciated I have the flowing text 235543 123 45654 199 225 578 45654 199 225 I need to find this sequence from A file 45654 199 225 (22 Replies)
Discussion started by: khaled79
22 Replies

6. Homework & Coursework Questions

[solved]Perl: Printing line numbers to matched strings and hashes.

Florida State University, Tallahassee, FL, USA, Dr. Whalley, COP4342 Unix Tools. This program takes much of my previous assignment but adds the functionality of printing the concatenated line numbers found within the input. Sample input from <> operator: Hello World This is hello a sample... (2 Replies)
Discussion started by: D2K
2 Replies

7. UNIX for Dummies Questions & Answers

Finding numbers in lines with strings and number and doing some manipulation

Hi, I want to write a script that does something like this: I have a file, in which in every line, there is a string of words, and followed by some space, a number. Now, I want to identify the line, which has the largest startFace number (say m=8118), take that number and add it to the... (2 Replies)
Discussion started by: super_commando
2 Replies

8. UNIX for Dummies Questions & Answers

How to Convert Strings into Numbers under C-Shell?

I tried something like: set test3 = (4.985e-10 5.130e-10 5.486e-10 6.023e-10 7.015e-10) set test4 = (4.869e-10 5.010-10 5.363e-10 5.895e-10 6.887e-10) set test5 = $test3 - $test4 but this doesn't seem to work. And then I tried: @ test5 = $test3 - $test4 This doesn't seem to work... (8 Replies)
Discussion started by: EDALBNUG
8 Replies

9. Shell Programming and Scripting

extracting numbers from strings

Hello all, I am being dumb with this and I know there is a simple solution. I have a file with the follwing lines bc stuff (more)...............123 bc stuffagain (moretoo)............0 bc stuffyetagain (morehere)......34 failed L3 thing..............1 failed this... (2 Replies)
Discussion started by: gobi
2 Replies

10. Shell Programming and Scripting

formatting output in human readable numbers

Hi, The following command provides the usage in 1024-byte blocks du -ks * | sort -n | echo "$1" ... 1588820 user10 2463140 user11 2464096 user12 5808484 user13 6387400 user14 ..... I am trying to produce an output of first coulmn by multiplying by 1024 so that the output should... (11 Replies)
Discussion started by: ghazi
11 Replies
Login or Register to Ask a Question