- 最後登錄
- 2023-5-13
- 在線時間
- 1 小時
- 註冊時間
- 2008-2-15
- 閱讀權限
- 20
- 精華
- 0
- UID
- 3511884
- 帖子
- 173
- 積分
- 363 點
- 潛水值
- 5633 米
| 若有安裝色情守門員,可用無界、自由門等軟件瀏覽伊莉。或使用以下網址瀏覽伊莉: http://www.eyny.com:81/index.php 本帖最後由 arthurliuliu 於 2014-6-3 08:31 AM 編輯
我用C#要讀取文字檔的數值來做計算,結果文字轉換成數值失敗,跑出來全部都是0,我用這個程式來讀另一個文字檔就沒問題,到底問題出在那裡呢?誰能幫我看一下
以下是我的c#程式
- public static void Main()
- {
- string path;// = @"test.txt";
- string save;// = @"savedfile.xls";
- Console.WriteLine("Please input load file name:");
- path= Console.ReadLine();
- Console.WriteLine("Please input save file name:");
- save = Console.ReadLine();
- // 檔案既已建立,利用OpenText()方法予以讀出
- // 除了建構StreamReader物件的方式不同外,其後讀取的手法
- // 與直接利用StreamReader建構物件的作法殊無二致!
- StreamReader sr = File.OpenText(path);
- string[] separators = { " ", "," };
- string value,strtotal="";
-
- int num,total=0;
- int i=0,j;
- // 每次讀取一列,並存入變數value,直到檔案結束
- // 將讀入的資料秀出
-
- Console.WriteLine("\n逐列讀取檔案所有內容:使用StreamReader物件");
- while ((value = sr.ReadLine()) != null)
- {
- j=0;
- i++;
- string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
- foreach (var word in words)
- {
- j++;
-
- try
- {
- num = Convert.ToInt16(word);
- if (i <= 3)
- {
- if (j > 3)
- {
- Console.Write(num + "\t");
- total += num;
- }
- }
- else
- {
- return;
- }
- }
- catch
- {
- continue;
- }
- }
- Console.WriteLine(total);
- strtotal += Convert.ToString(total)+"\t";
- File.WriteAllText(save, "\t"+strtotal);
- total = 0;
- }
複製代碼
我的文字檔資料如下
A_X [lsb] A_Y [lsb] A_Z [lsb] A_X [mg] A_Y [mg] A_Z [mg] A_X [deg] A_Y [deg] A_Z [deg] A_INT1 A_INT2 M_X [lsb] M_Y [lsb] M_Z [lsb] M_X [mG] M_Y [mG] M_Z [mG] Heading [deg] G_X [lsb] G_Y [lsb] G_Z [lsb] G_X [dps] G_Y [dps] G_Z [dps]
-2 -1 68 -24 -12 816 -1 0 88 0 0 15 -107 -209 22 -159 -348 276 -73 13 -61 -1 0 -1
0 0 67 0 0 804 0 0 90 0 0 16 -107 -205 23 -159 -341 275 -11 -14 -87 0 0 -1
1 0 66 12 0 792 0 0 89 0 0 16 -107 -205 23 -159 -341 275 -65 -6 -62 -1 0 -1
-2 -1 64 -24 -12 768 -1 0 88 0 0 15 -108 -206 22 -161 -343 274 -33 -31 -67 0 0 -1
0 0 66 0 0 792 0 0 90 0 0 15 -108 -206 22 -161 -343 274 19 -18 -81 0 0 -1
0 0 65 0 0 780 0 0 90 0 0 15 -108 -206 22 -161 -343 275 -108 -19 -30 -1 0 0
1 1 66 12 12 792 0 0 89 0 0 15 -108 -206 22 -161 -343 275 -58 -9 -48 -1 0 0
-1 -1 65 -12 -12 780 0 0 89 0 0 15 -108 -206 22 -161 -343 275 -49 0 -69 0 0 -1
誰能幫我解答?感激不盡
程式碼未依規定包覆,板主代為編輯。另文字檔部分請直接置於附件,不然版面很亂,謝謝。
... |
|