获取文件每行中的数字总和
我有一个文件,其中有一些数字,我想将每行中的第一个数字与第二个数字相加。这是我的文件中的数字:
-944 -857
-158 356
540 70
15 148
例如,我想对 -944 和 -857 求和,我应该做什么? 我像下面的代码一样检查数字是什么,输出是-158和15(它不显示-944和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]);
}
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
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]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在
while
检查中读取一行,然后再次解析该值 - 这就是为什么它似乎只读取偶数行。建议的解决方案:
更新:使用
string.Split()
的重载,不返回空结果,最多返回 2 个值(1 和字符串的其余部分)。You are reading a line in the
while
check, and then again to parse the value - which is why it only seems to read the even lines.Proposed solution:
update: using an overload of
string.Split()
that returns no empty results and max 2 values (1 and the rest of the string).试试这个(简化版本):
您正在阅读两次,但只使用第二次阅读。
注意:您也不会从行的开头修剪空格,因此如果数据有前导空格,您将丢失数字(如示例所示)。
Try this (streamlined version):
You are reading twice but only using the second read.
Note: You are also not trimming spaces from the start of the lines so you will lose numbers if the data has leading spaces (as shown in the example).
您正在 while 条件中执行 readline,然后在 while 作用域主体中再次执行 readline,从而跳过 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: