[英]StreamWriter writing a text file's content incorrectly
我正在使用StreamWriter
類將一些文本寫入新創建的文本文件,但輸出總是奇怪錯誤,這是我的代碼:
StreamWriter sw = new StreamWriter("newtextfile.txt", false, Encoding.Unicode);
for (int d = 0; d < count; d++)
{
sw.WriteLine(d + '^' + str1[d] + '^' + str2[d] + '^' + str3[d]);
}
sw.Flush();
sw.Close();
輸出如下(這是文件的開頭):
65342STR1^STR2^STR3
65343STR1^STR2^STR3
...等等
我不知道為什么WriteLine
跳過d + '^'
並寫出那個隨機數。
嘗試使用"
:
sw.WriteLine(d + "^" + str1[d] + "^" + str2[d] + "^" + str3[d]);
用表達式
int d = 0;
var t = d + '^'; // int + char
t
類型是int
,而不是string
。
在您的情況下, 65342
( == 0xFF3E
)出現,因為它是這個特殊的類似^
字符的Unicode(全寬旋轉重音)。
它將char字面'^'的整數值添加到d,所以如果d=123
則d + '^' = 217
。 請改用字符串文字。
sw.WriteLine(d + "^" + str1[d] + "^" + str2[d] + "^" + str3[d]);
問題是這個表達式:
d + '^'
不涉及任何字符串。 它試圖添加一個int
和一個char
,它通過將char
提升為int
(其值為65342,因為它是'^'
的UTF-16代碼單元),然后執行正常的數字加法。 然后結果(一個int
)被轉換為一個字符串,因為后面的+
運算符是str1[d]
作為它的右邊操作數。
您可以使用字符串文字:
d + "^" + ...
但我個人會使用格式代替:
sw.WriteLine("{0}^{1}^{2}^{3}", d, str1[d], str2[d], str3[d]);
在我看來,這更容易閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.