我正在编写一个简单的函数,用于我的一个实用程序实现文件。我最近发现——在使用其中一个 C++17 库时——使用对的std::filesystem::path::string()
调用中的函数输出目录条目printf()
只会导致将一串奇数字符发送到STDOUT
。使用cout
结果没有问题。代码如下:
if( !initialized )
{
try
{
const filesystem::path MODELS_DIRECTORY = R"(C:\-----\-----\-----\models)";
const filesystem::path RESOURCES_DIRECTORY = filesystem::relative(R"(\Resources)", MODELS_DIRECTORY);
for( const filesystem::directory_entry& dir_entry : filesystem::directory_iterator{ MODELS_DIRECTORY } )
{
string test = "this\\is\\a test\\";
string directory = dir_entry.path().string();
printf("%s\n", test);
//cout << directory << endl;
}
}
catch( filesystem::filesystem_error& fs_err )
{
printf( "fs exception caught in GraphicsDataCatalog::InitCatalog()" );
}
initialized = true;
}
使用由 组成的测试机制std::string test
并调用printf()
表明双反斜杠是罪魁祸首。删除字符串中的空格并不能解决问题——我假设也许有一个格式说明符可以解决打印到控制台的不稳定字符。使用cout
调用string
返回的dir_entry.path().string()
可以成功。
有人对这个主题有更多的了解吗?
MRE(最小可重复示例):
#include <iostream>
using namespace std;
int main()
{
const string PASS_STRING = "This is a test.";
const string FAIL_STRING = "This\\is not\\a\\test.";
cout << PASS_STRING << endl;
cout << "Test passed.\n" << endl;
printf( "%s\n", FAIL_STRING );
printf( "Test failed.\n" );
return 0;
}
格式
%s
说明符采用char *
,而不是std::string
。您向 传递了错误的参数类型printf
。