2016-01-06 37 views
0

我从文本文件input.txt中读取2个输入。我有文本文件作为在c中逐行读取文件#

12#15#

17#71#

18#15#

我已经使用这个语法,但它会读取最后一行only.why它不工作?什么可能是最好的循环条件来读取线轮空线像12 + 15,并显示27和阅读下一行17 + 71,并显示88和过程最后

  StreamReader reader = new StreamReader("input.txt"); 
      string line; 
      int count = 0; 
      while ((line = reader.ReadLine()) != null) 
      { 
       string[] splitted = line.Split('#'); 
       string first = splitted[0].Trim(); 
       string second = splitted[1].Trim(); 
       x = Convert.ToInt32(first); 
       y = Convert.ToInt32(second); 
+0

所以你要总结所有的行,并显示它呢? – vilpe89

+0

你不能添加字符串。 +符号是一个串联。您需要将字符串转换为整数,然后进行求和。将该求和转换回字符串,然后显示它。 – ZaXa

+0

@ZaXa,哇,我没有注意到,这是相当新手questioon :) @ sangam-jung use'sum = Convert.ToInt32(first)+ ....'等 –

回答

0

一般的答案 你应该追加到文本框中,但是你在每个循环迭代中覆盖它。

我建议将txtSum.Text分配移出循环,只能运行一次,因为txtSum.set_Text是涉及图形重绘并且代价高昂的操作。

样品

try 
{ 
    StreamReader reader = new StreamReader("input.txt"); 
    string line; 
    StringBuilder sum = new StringBuilder(); 
    int count = 0; 
    while ((line = reader.ReadLine()) != null) 
    { 
     string[] splitted = line.Split('#'); 
     string first = splitted[0].Trim(); 
     string second = splitted[1].Trim(); 
       sum.Append(first).Append(second); 

    } 
     txtSum.Text = sum.ToString(); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message); 
} 
+0

我已经更新了前一个 –