3

I have some C++ code where I need to use CString with sprintf. In this code I'm creating file names that are CStrings that are defined by sprintf. The code is below.

double Number;     
Number = 0.25; 

char buffer [50];

CString sFile;
sFile = sprintf(buffer,"TRJFPICD(%3.3f).txt",Number);

CString SFFile;
SFFile = sprintf(buffer,"TRJFPICV(%3.3f).txt",Number);

CString SFFFile;
SFFFile = sprintf(buffer,"TRJFPICA(%3.3f).txt",Number);

The desired file names are TRJFPICD(0.25).txt, TRJFPICV(0.25).txt, and TRJFPICA(0.25).txt. I have to use CStrings for my code.

The error I get is 'operator =' is ambiguous.

us2012
  • 16,083
  • 3
  • 46
  • 62
  • 1
    `sprintf` returns `int` – why would you expect to assign an `int` to a `CString`? Also, use `_stprintf` instead of `sprintf` to avoid unicode issues, or better yet use `CString::Format` instead of any `sprintf` variant. – ildjarn Feb 19 '13 at 22:14
  • 1
    Instead of `sprintf`, you could use the `Format` method on the `CString` itself. – jxh Feb 19 '13 at 22:14
  • Use this msdn link to find out the exact way of using sprint to copy data into CString object: http://msdn.microsoft.com/en-us/library/aa300569(v=vs.60).aspx – roymustang86 Feb 19 '13 at 22:16

1 Answers1

6

Take a look at CString::Format (ignore the CStringT part - CString is derived from CStringT). It does what you want and allows you to rewrite your code cleanly:

double Number = 0.25; 

CString sFile;
sFile.Format(_T("TRJFPICD(%3.3f).txt"), Number);

CString SFFile;
SFFile.Format(_T("TRJFPICV(%3.3f).txt"),Number);

CString SFFFile;
SFFFile.Format(_T("TRJFPICA(%3.3f).txt"),Number);
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
  • 1
    Thank you so much. I'm NOT a C++ programer. I'm a structural engineer working on my PhD, and I have to use object oriented C++ programing to work with my advisor. When I graduate I will never do objected oriented MFC programing again. – Grady F. Mathews Iv Feb 19 '13 at 22:26
  • 2
    @Grady : For being forced to use MFC alone you have my sympathies. – ildjarn Feb 20 '13 at 00:39
  • Hey! It's a Ph.D.! He's supposed to suffer a little! – Nik Bougalis Feb 20 '13 at 00:40