簡體   English   中英

從文本文件中讀取和解析整數

[英]Reading and parsing integers from a text file

我正在嘗試從文本文件中獲取一行整數並將它們解析為單獨的變量。 文本文件設置如下:

ID:HP:MP:STR:WIS:SPD:GOLD:XP

0:100:50:10:5:12:5:10

我想在它們之間用: 符號分割它們。 我遇到的問題之一是能夠逐行讀取文件作為字符串,解析它們,然后將解析的字符串存儲為整數。 這是我到目前為止嘗試使用的代碼:

class monster
{
    string line;
    string[] mstats;
    string[] mname;
    char[] delimeterChars = {':'};
    int id;
    int i = -1;
    int j = 0;
    int hp;
    int mp;
    int str;
    int wis;
    int spd;
    int gold;
    int xp;

    public monster(int id)
    {
        StreamReader stats = new StreamReader("monsterStats.txt");
        while(i != id)
        {
            i++;
            line = stats.ReadLine();
            mstats = line.Split(delimeterChars);
            j = 0;
            foreach(string s in mstats)
            {
                if (j == 0) id = int.Parse(s);
                else if (j == 1) hp = int.Parse(s);
                else if (j == 2) mp = int.Parse(s);
                else if (j == 3) str = int.Parse(s);
                else if (j == 4) wis = int.Parse(s);
                else if (j == 5) spd = int.Parse(s);
                else if (j == 6) gold = int.Parse(s);
                else if (j == 7) xp = int.Parse(s);
                j++;
            }
        }
        curHp = hp;
        curMp = mp;
        curSpd = spd;
        curStr = str;
        curWis = wis;
    }
}

運行此代碼時出現以下錯誤:

輸入字符串的格式不正確。 它引用了這部分代碼:

if (j == 0) id = int.Parse(s);

為什么是foreach 怎么樣:

id = int.Parse(mstats[0]);
hp = int.Parse(mstats[1]);

等等。 事先檢查mstats是否足夠長。

一點 Linq 可以讓您一次性獲得一個整數數組:

int[] fields = line.Split(delimeterChars).Select(s => int.Parse(s)).ToArray();

id = field[0];
hp = field[2];

至於讓代碼正常工作,請嘗試在將文本傳遞給 Parse 之前打印出文本行和每段文本。 如果不是 integer,那就是你的問題。

嗯,第一件事是找出錯誤的輸入是什么。

如果您預期輸入數據錯誤,請使用int.TryParse而不是僅使用int.Parse 如果您沒有預料到錯誤的輸入數據,那么它引發異常的事實可能是合適的 - 但您應該檢查您的數據以找出問題所在。

我還建議進行一次解析調用,而不是每次都進行。 這不像您正在為每個字段進行不同類型的解析。

解析文本輸入的一個非常好的方法總是正則表達式。

Regex r = new Regex(@"(?<id>\d+):(?<hp>\d+):(?<mp>\d+):(?<str>\d+):(?<wis>\d+):(?<spd>\d+):(?<gold>\d+):(?<xp>\d+)");

// loop over lines
Monster m = new Monster();
Match mc = r.Match(input);

m.hp = GetValue(mc.Groups["hp"], m.hp);
m.mp = GetValue(mc.Groups["mp"], m.mp);
m.str = GetValue(mc.Groups["str"], m.str);
...


// method to handle extracted value
private static int GetValue(Group g, int fallback)
{
    if (g == null) throw new ArgumentNullException("g");
    return g.Success ? Convert.ToInt32(g.Value) : fallback;
}

GetValue 方法檢查提取的值。 如果匹配失敗(可能是“”或“AB”而不是數字 - g.Success 為假),您可以按照您想要的方式處理它。 以我的方式,我只是使用后備值。

http://msdn.microsoft.com/en-us/library/hs600312.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM