简体   繁体   中英

Repeat a char a variable amount of times in C++ using CString

I am using fprintf to output data to a .txt file. So far I have:

FILE * pFile;
CString equalSignsC('=', 80);
CString FileName(name.project.c_str());
FileName += "Stats.txt";
pFile = _wfopen(FileName, _T("w"));
fprintf(pFile, "%s", equalSignsC);
fclose(pFile);

I want to create a CString that repeats the character '=' 80 times but when I look at my output, '=' is only printed once. I'd like to avoid using ofstream when writing to a file and I'd also like to avoid using a loop to print out the equal signs. Thoughts?

The problem is that you're mixing ANSI/UNICODE functions and datatypes, you open with _wfopen which is correct for unicode, but try to write a unicode string with an ansi version of the function(fprintf).

fwprintf(pFile, L"%s", equalSignsC); solves your problem.

EDIT: To clarify a bit with regards to what the others have posted.

It's safe to assume your project is set to Unicode, otherwise your _wfopen would have failed to compile.

Mixing std::string and CString is perhaps weird, but sometimes necessary when working with different interfaces.

Constructing a CString from std::string.c_str() is perfectly fine for both Unicode and ANSI builds since CString constructor overloads take care of conversion if you build in Unicode and provide an ANSI string and vice versa.

Your way of initializing the CString with '=' signs is also perfectly fine, and works.

The only problem is the fprintf(and format string) which should be fwprintf since you're using Unicode build.

The CString constructor does what you ask. The problem is in your environment, and how you print out the result.

First you have to be sure whether you're working with Ascii (8 bit) or Unicode (16 bit) strings. You don't make this clear in your example. I shall assume it's Ascii.

Second, to treat a CString as a plain old C string you have to cast it. So:

printf("%s", (LPCTSTR)equalSingsC);

This is not needed if you use stream I/O.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM