printf 内部与外部 C++ 字符串转换

C++ string conversion inside vs outside printf

我正在使用 Poppler 从 PDF 中提取文本并使用以下代码打印文本:

for (std::vector<poppler::text_box>::iterator it = currpg.begin(); it != currpg.end(); ++it)
{
    const char *txt = it->text().to_latin1().c_str();
    printf("%s\n", txt);
}

除了一个字符串“Exemptions/Allowances:”之外的所有字符串都工作正常,结果为 Ы`L/V.

然后我尝试了以下代码并正确打印了字符串:

for (std::vector<poppler::text_box>::iterator it = currpg.begin(); it != currpg.end(); ++it)
{
    std::string txt = it->text().to_latin1();
    printf("%s\n", txt.c_str());
}

对于那个特定的字符串,为什么在 printf 内部转换为 c_str 会产生与在 printf 外部完成转换时不同的结果?我想可能是“/”引起了问题,但有些日期字符串也有“/”并且打印正确。

指针 txt 比临时变量还长。

it->text().to_latin1() // returns a temporary
const char *txt = it->text().to_latin1().c_str(); // stores the pointer to an internal buffer of the temporary
printf("%s\n", txt); // the temporary destroyed, the dangling pointer is used

第一个例子涉及未定义的行为。

您的问题是重复的。参见 std::string::c_str() and temporaries


如果您使用了 C++ 的强大功能,您会编写出更短、更安全的代码。比较

std::string txt = it->text().to_latin1();
printf("%s\n", txt.c_str());

std::cout << it->text().to_latin1() << "\n";