简体   繁体   English

Fprintf奇怪的调试输出

[英]Fprintf bizarre output on Debug

I'm trying to write a function that prints the local time plus the given string, and appends a newline character at the end for readability. 我正在尝试编写一个函数,该函数打印本地时间和给定的字符串,并在末尾附加换行符以提高可读性。

Thats the current code: 那就是当前代码:

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);
}

The output is the one I was expecting on Release mode. 输出是我在发布模式下期望的输出。 On the working program ErrorLog.txt has this new line, as intended: 在工作程序中,ErrorLog.txt按预期具有此新行:

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

But on debug mode, the output seems to have taken a random string. 但是在调试模式下,输出似乎采用了随机字符串。 These are two consecutive outputs, random without apparent explanation to me: 这是两个连续的输出,对我来说没有明显的解释是随机的:

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

The function is given a hard-coded string on call, so the input of errLog is exactly the same. 该函数在调用时被赋予了一个硬编码的字符串,因此errLog的输入是完全相同的。

You need to use c_str() to access the character pointer to pass to fprintf: 您需要使用c_str()访问字符指针以传递给fprintf:

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

It's also generally more efficient in most cases to accept your parameter as a const reference const std::string& errorString than to force construction of a new string for the parameter when it may not be required. 通常,在大多数情况下,将您的参数作为const引用const std::string& errorString比在不需要该参数时强制构造一个新字符串更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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