我試圖做一個函數,使C++ WinAPI應用程序中組合C字符串和std::string
更容易一些。的結合std :: strings和C-Strings導致緩衝區溢出
所以不是這樣:
TCHAR res[MAX_PATH];
_stprintf(res, _T("In functionX(): error occured where the variable values are %d, %u, %s, %c"), myInt, myUnsignedInt, myStr.c_str(), myChar);
MessageBox(NULL, res, _T("Error Occurred"), MB_OK);
我只是要做到這一點(這使得它更容易一些合併不同的字符串類型,因爲我沒有保持到處宣稱TCHAR數組):
tstring res = concat(_T("In functionX(): error occured with the variable values %d, %u, %s, %c"), myInt, myUnsignedInt, myStr.c_str(), myChar);
MessageBox(NULL, (LPTSTR)res.c_str(), _T("Error Occurred"), MB_OK);
我的問題: My功能的concat();失敗,當我通過參數格式超過1個變量,我不知道爲什麼?
// The following function call causes the error
tstring ou = concat(_T("In functionX(): Failed to create temp file - %s - %s\r\n"), (LPTSTR)tempFileRootDir.c_str(), tempFile);
tstring WinFile::concat(TCHAR* strFormat, TCHAR* format, ...)
{
// tstring is either a std::string or std::wstring depending on whether unicode is used
// Post: Wrapper function to easily merge C++ strings with C Strings
va_list arguments;
va_start(arguments, format);
TCHAR res[MAX_PATH];
_stprintf(res, strFormat, format);
return tstring(res);
}
,當我在微軟的Visual C運行函數是發生++的錯誤:
緩衝區溢出發生在Application.exe具有 損壞了程序的內部狀態。按Break鍵調試 程序或繼續終止程序。
有關更多詳細信息,請參閱幫助主題'如何調試緩衝區溢出 問題'。
爲什麼要聲明res具有MAX_PATH字符?你並沒有複製到它的路徑。據猜測,我會說你想寫超過MAX_PATH字符來解析。 –
作爲一個選項,你可以使用ATL :: CString。它有Format方法。 –
上傳'STD'的任何特殊原因?這通常意味着性傳播疾病,不是嗎? C++標準庫名稱空間是'std',小寫。 – jalf