获取每行文件中的数字总和 [英] Getting Sum Of Numbers In Each Line Of File
本文介绍了获取每行文件中的数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,其中有一些数字,我想将每一行中的第一与第二相加.这是我的文件中的数字:
i have a file that there is some numbers that i want to sum number one with number two in each line.here is numbers in my file:
-944 -857
-158 356
540 70
15 148
例如我想求和 -944 和 -857 我该怎么办??我像下面的代码一样检查数字是什么,输出是 -158 和 15(它没有显示 -944 和 540 !!!):
for example i want to sum -944 and -857 what should i do?? i did it like the code below to check whats the numbers and the output is -158 and 15(it doesnt show -944 and 540 !!!):
StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
while (ar.ReadLine() != null)
{
string[] spl = ar.ReadLine().Split(' ');
MessageBox.Show(spl[0]);
}
推荐答案
您正在 while 条件中执行 readline,并在 while 范围的主体中再次执行,因此跳过了 1 个 readline 指令(在 while 条件中).试试这个:
you're doing a readline in your while condition and again in the body of your while scope, thus skipping 1 readline instruction (in the while condition). try this instead:
StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
string s = ar.ReadLine();
while (s != null)
{
//string[] spl = s.Split(' ');
// below code seems safer, blatantly copied from one of the other answers..
string[] spl = s.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
MessageBox.Show(spl[0]);
s = ar.ReadLine();
}
这篇关于获取每行文件中的数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文