我正在讀取帶有數字的檔案,然后當我嘗試將其轉換為 Int 時出現此錯誤,System.FormatException:'輸入字串格式不正確。' 閱讀檔案有效,我已經測驗了所有這些,無論我嘗試什么,它似乎都卡在了這個問題上。這是我到目前為止所做的:
StreamReader share_1 = new StreamReader("Share_1_256.txt");
string data_1 = share_1.ReadToEnd();
int intData1 = Int16.Parse(data_1);

然后如果 parse 在它不列印任何東西。
uj5u.com熱心網友回復:
正如我們在您的帖子中看到的,您的輸入檔案包含的不是一個數字,而是多個。因此,您需要遍歷檔案的所有行,然后嘗試決議字串的每一行。
編輯:舊代碼使用外部庫。對于原始 C#,請嘗試:
using (StringReader reader = new StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with the line
}
}
此外,我鼓勵您始終使用TryParse方法將字串決議為數字,而不是Parse方法。
您可以在 C# 中找到該常見問題的一些詳細資訊和不同的實作:C#: Looping through lines of multiline string
uj5u.com熱心網友回復:
決議每一行
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
int intData1 = Int16.Parse(line);
}
uj5u.com熱心網友回復:
您可以在class 和LinqStreamReader的幫助下簡化代碼并擺脫:File
// Turn text file into IEnumerable<int>:
var data = File
.ReadLines("Share_1_256.txt")
.Select(line => int.Parse(line));
//TODO: add .OrderBy(item => item); if you want to sort items
// Loop over all numbers within file: 15, 1, 48, ..., 32
foreach (int item in data) {
//TODO: Put relevant code here, e.g. Console.WriteLine(item);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453332.html
