调试时Fprintf奇怪的输出

时间:2014-09-16 09:10:25

标签: c++ visual-studio-2012 printf stdio

我试图编写一个打印本地时间加上给定字符串的函数,并在末尾添加换行符以便于阅读。

这是当前的代码:

void errLog(const std::string errorString)
{
    FILE* errorLog;
    fopen_s(&errorLog, "ErrorLog.txt", "ab+");
    time_t rawTime;
    time (&rawTime);
    struct tm errorTime;
    localtime_s(&errorTime, &rawTime);
    char timeString[20];
    strftime(timeString, 20, "%d-%m-%Y %H:%M:%S", &errorTime);
    fprintf(errorLog, "%s Error: %s\n", timeString, errorString);
    fclose(errorLog);
}

输出是我在发布模式下所期待的输出。在工作程序上,ErrorLog.txt按照预期使用了这一新行:

16-09-2014 10:58:45 Error: devFont.ttf load failed

但是在调试模式下,输出似乎采用了随机字符串。这是两个连续的输出,随机而没有明显的解释:

16-09-2014 11:13:57 Error: ΘυB
16-09-2014 11:14:09 Error: Μϊ;

该函数在调用时被赋予硬编码字符串,因此errLog的输入完全相同。

1 个答案:

答案 0 :(得分:1)

您需要使用c_str()来访问要传递给fprintf的字符指针:

fprintf(errorLog, "%s Error: %s\n", timeString, errorString.c_str());

在大多数情况下,接受您的参数作为const引用const std::string& errorString通常也比在不需要时强制构造参数的新字符串更有效。

相关问题