Search code examples
c++printfcstring

Use CString with sprintf


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.


Solution

  • 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);