CString::Format 的替代方案?

2022-01-12 00:00:00 string format c++ mfc

在 VC6 中进行字符串格式化是否有更好的替代方法,在替换之前进行语法检查?

Is there any better alternative for doing string formatting in VC6, with syntax checking before substitution?

推荐答案

CStringprintf 样式的格式提供了 Format 方法,但是这不是类型安全的.

CString offers the Format method for printf-style formatting, but this isn't type-safe.

对于类型安全的字符串格式,您可以使用 std::stringstream/std::wstringstream 或 Boost Format 库,尽管它们都适用于 C++ std::basic_string 类模板,而不是 MFC CString 类.我已经在 VC6 中成功使用了这两个.

For type-safe string formatting you could either use std::stringstream / std::wstringstream or the Boost Format library, although these both work with the C++ std::basic_string class template, and not the MFC CString class. I've used both of these successfully in VC6.

Boost Format 很好,因为它允许您使用类似 printf 的语法,并且如果您提供的参数与格式字符串不匹配,则会抛出异常,而使用 C++ iostreams 进行字符串格式化往往使您的代码非常冗长.

Boost Format is nice because it allows you to use printf-like syntax, and will throw an exception if the arguments you supply don't match the format string, whereas string formatting with C++ iostreams tends to make your code quite verbose.

请注意,您可以从 std::string 创建一个 CString 对象,如下所示:

Note that you can create a CString object from a std::string as follows:

std::string s;
CString str( s.c_str() );

我希望这会有所帮助!

相关文章