• Status: Solved
• Priority: Medium
• Security: Public
• Views: 248

# Need some help with a CString

I would like to build  a CString like the following:

I want to fill the string with 2 numbers  1)doulbe  2)int
The string should always be 8 bytes long

I also want to fill the 4-6 bytes with " x "

CString A="1.50 x 1500"
or
"5.00 x   100"
"0.55 x     10"
"0.01 x   500"
|
length=8      012345678

In my old days with business basic I had a function like this one:
int y=200;
Y\$ =  y using "####"

double d=0.55
D\$ = d using  "##.##"
So I can easly build a String like this "0.55 x  200"          String =  D\$+" x "+Y\$
012345678

Is there anything in C++ that I can easy build a string with numbers?
So the string is trimed right?

Please let me know, thanks.
500 points.
Best regards,
Thomas

0
Thomas Stockbruegger
3 Solutions

Commented:
You can go 2 ways about it.
1) Make a function:
void SetString(CString* str, double dNum, int nNum)
{
str->Format("%.2f x %d", dNum, nNum)
}

// you can make if statements for numbers under 10 and over 10 and add spaces or zeroes
to the format string accordingly to make sure the string is always 8 char long.

2) You can inherit a CString class and add a member function to format the string, this will require more
code and will add complexity to your code, I would personally juts make the function and just call it whenever I need it.

Reference: http://msdn2.microsoft.com/en-us/library/wc7014hz(VS.71).aspx
0

Commented:
It's what gravit9 said.
One tiny correction though, the %d should be %3d or %4d, where the number between % and 'd' is the number of digits you want for the integer.

By the way, the examples you have given are bigger than 8 characters.
"1.50 x 1500"
1.50 = 4 chars
space x space = 3 chars
1500 = 4 chars
0

Commented:
You can use stringstream classes to format strings:

// put that below #include "stdafx.h"

#include <sstream>
#include <iomanip>
using namespace std;

CString A;
double d1 = 1.5;
int        i2  = 1000;
ostringstream oss;

oss << setw(4) << right << d1 << " x " << setw(4) << right << i2;
CString A = oss.str().c_str();

setw(4) makes the next column 4 bytes.
right makes the next output right-justified.

oss.str() gets the std::string from the ostringstream.
oss.c_str() gets a 'const char*' from the std::string what can be assigned to a CString.

Regards, Alex

0

Author Commented:
thanks for the help
Best regards from
Thomas
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.