簡體   English   中英

此代碼的意外結果

[英]Unexpected result from this code

我有一個聲明為的對象:

private string SourceProgram;

基本上我想使用下面的代碼來解析一些東西:

 private void LabelScan(System.IO.BinaryWriter OutputFile, bool IsLabelScan)
        {

            if (char.IsLetter(SourceProgram[CurrentNdx]))
            {
               if (IsLabelScan) LabelTable.Add(GetLabelName(), AsLength);
                while (SourceProgram[CurrentNdx] != '\n')
                    CurrentNdx++;
                CurrentNdx++;
                return;
            }
            EatWhiteSpaces();
            ReadMneumonic(OutputFile, IsLabelScan);
        }

但是我在執行時遇到錯誤:

-       SourceProgram[CurrentNdx]   
'SourceProgram[CurrentNdx]' threw an exception of 
type 'System.IndexOutOfRangeException'  char {System.IndexOutOfRangeException}

-       base    {"Index was outside the bounds of the array."}
    System.SystemException {System.IndexOutOfRangeException}

並且CurrentNdx值為46。

出了什么問題。 字符串變量SourceProgramlength < 46

如果是,如何解決此代碼?

該代碼似乎在字符串SourceProgram中尋找換行符。 也許SourceProgram不包含\\ n?

當然最好使用int position = SourceProgram.indexOf("\\n")來找到\\ n的位置

另外,您似乎沒有在此代碼中將CurrentNdx重置為零,這可能在其他地方需要

while (SourceProgram[CurrentNdx] != '\n')
                    CurrentNdx++;

也許您的SourceProgram字符串不包含換行符,或者在CurrentNdx超出字符串中的任何換行符之后調用該函數。

是的,此錯誤表明SourceProgram的字符數少於47。 我們幾乎可以在不看SourceProgram內容的情況下告訴您所有這些。

暫無
暫無

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

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