2012-06-20 57 views
0

我使用英巴卡迪諾C++ Builder的XE和我想寫123456這樣的文本文件:空間字符串中的

String teststring = "123456"; 
int iFileHandle = FileCreate("example.txt"); 
int iLength = teststring.Length()*sizeof(wchar_t); 
int output = FileWrite(iFileHandle, teststring.w_str(), iLength); 

但輸出是這樣的:

1 2 3 4 5 6 

在每個字符後都添加了空格。我可以看到iLength是12,創建字符串時添加的空格也是如此,我該如何防止這種情況發生?

+2

我要去上肢體和猜與您使用寬字符字符串打印 –

回答

0

你可以使用一個字符串列表並添加你想要的字符串,然後將字符串列表保存到文件中。

TStringList *Temp = new TStringList(); 
Temp->Add("123456"); 
Temp->SaveToFile(("example.txt"); 

delete Temp; 
+0

謝謝!這對我來說是寫入文件的更好方法。 – Blacktron

0

iLength應該是12,因爲在這種情況下字符串長度是6並且wchar_t的大小是2。 所以,確實在創建字符串時不會添加空格。這些2.,4,6,8和10字節分配,當你從字符串這裏創建一個寬字符串初始化爲空格字符:

teststring.w_str() 

使用c_str(嘗試)代替:

String teststring = "123456"; 
int iFileHandle = FileCreate("example.txt"); 
int iLength = teststring.Length(); 
int output = FileWrite(iFileHandle, teststring.c_str(), iLength); 
+0

感謝您的解釋,但更改代碼像您建議的iLength 6,但文本文件中的文本是「1 2 3」。 – Blacktron

1

System::String在XE中編碼爲UTF-16,它使用16位值。您看到的那些「空格」是這些字符值的高位字節,它們是ASCII字符值的空值。如果你不想在你的文件的字節,那麼你必須在String轉換爲不同的編碼,不使用它們,例如:

String teststring = "123456"; 
AnsiString s = teststring; // or UTF8String, or any other MBCS encoding you want 
int iFileHandle = FileCreate("example.txt"); 
int iLength = s.Length() * sizeof(AnsiChar); 
int output = FileWrite(iFileHandle, s.c_str(), iLength);