2015-09-07 85 views
2

我有寫出每當拍攝照片時照相機在幀號和當前系統時間的程序:C++奇怪的字符出現

SYSTEMTIME st; 
GetSystemTime(&st); 
lStr.Format(_T("%d %d.%d.%d.%d\r\n"),GetFrames() ,st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); 

std::wfstream myfile; 
myfile.open("test.txt", std::ios::out | std::ios::in | std::ios::app); 
    if (myfile.is_open()) 
      { 
      myfile.write((LPCTSTR)lStr, lStr.GetLength()*sizeof(TCHAR)); 
      myfile.close(); 
      } 
     else {lStr.Format(_T("open file failed: %d"), WSAGetLastError()); 
     } 

的文本文件,該程序輸出似乎正確地寫入數據,但是我得到的空格和字符不應該在每行的開頭。該網站似乎並沒有正確地格式化的空間,所以我會後一幅畫,這是文本文件的樣子。該文件還有時顯示除了零之外的項目符號點。

enter image description here

正如你所看到的第一行是不錯,但它似乎變得更糟的時間越長我寫的文本文件。該程序每秒鐘向該文件寫入約10次。我是C++的新手,我不確定可能會導致這種情況。我試圖尋找類似的其他問題,但他們似乎沒有我正在尋找的解決方案。任何幫助,將不勝感激。

+0

是什麼GetFrames返回?詮釋? –

+0

我懷疑它是在該行的末尾的'\ r \ N'。正如你在文本格式打開它(IE,而不是二進制)\ n將被自動轉換爲「\ r \ n」在Windows上。 –

+0

這是一個DWORD,我應該使用一個DWORD? – oodan123

回答

2

的解決方案具有兩個部分:

lStr.Format(_T("%d %d.%d.%d.%d\r\n"),GetFrames() ,st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); 

應該是

lStr.Format(_T("%lu %d.%d.%d.%d\n"),GetFrames() ,st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); 

作爲GetFrames()返回DWORD這是unsigned long和你正在寫該文件爲文本所以\n是根據操作系統的不同,將其轉換爲\r\n

另一部分是,wfstream::write第二個參數是字符數不的字節,

myfile.write((LPCTSTR)lStr, lStr.GetLength()*sizeof(TCHAR)); 

應該

myfile.write((LPCTSTR)lStr, lStr.GetLength()); 
1

當您使用std::wfstream::write(basic_ostream),它需要你的字符串的大小。您再次將該尺寸乘以* sizeof(TCHAR)。刪除這個額外的乘法應該簡單地解決你的問題。


雖然如果您還有其他問題(例如,第三方庫返回的空間太多),您可以隨時修剪字符串。

一種用於這個基本的例子:

template<class TString> 
static inline TString &trim_left(TString &s) 
{ 
    s.erase(std::begin(s), std::find_if(std::begin(s), std::end(s), std::not1(std::ptr_fun<int, int>(std::isspace)))); 
    return s; 
} 

template<class TString> 
static inline TString &trim_right(TString &s) 
{ 
    s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), std::end(s)); 
    return s; 
} 

template<class TString> 
static inline TString &trim(TString &s) 
{ 
    return trim_left(trim_right(s)); 
}