如何解决错误“输入字符串格式不正确”? [英] How to solve error "input string was not in a correct format"?

查看:213
本文介绍了如何解决错误“输入字符串格式不正确”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前解决了这种类型的错误,但这次我被困了。

我有一个包含2,31,200个8和10位数的文件,我必须对每个数字中的所有数字求和然后将sum添加到列表中,但在添加总和时我得到了错误。 sum范围是0到90.我尝试'int,Int32,Int64'但是通过使用这些我得到了不同的错误对于Int32来说,值太大或太小。因此我使用'long '通过参考一些建议,但我的问题还没有解决,并得到另一个错误 -

下面是我的代码,我在行中出现上述错误

long sumOfnum =求和(Convert.ToInt64(Allbarcodes [i]));

我的代码出错了,请有人建议我。



我尝试过:



I solved this type of error previously but this time am getting stucked.
I have a file containing 2,31,200 numbers of 8 and 10 digits and i have to do sum all digits in each number then adding sum into a list, but while adding sums i got error. sum range is 0 to 90. I tried 'int, Int32, Int64' but by use of these i got different error "Value was either too large or too small for an Int32. hence im using 'long' by referencing some suggestions but my problem is not solved yet and getting another error-
Below is my code where Im getting above error in line
long sumOfnum = Summation(Convert.ToInt64(Allbarcodes[i]));
Whats wrong in my code please anyone suggest me way.

What I have tried:

public long Summation(long n)
     {
         long m, sum = 0;

         while (n != 0)
         {
             m = n % 10;
             sum = sum + m;
             n = n / 10;
         }
         return sum;
     }


 private void button2_Click(object sender, EventArgs e) // do task
     {
        List<long> barcodeList = new List<long>();

        using (FileStream fs = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read))
             using (StreamReader sr = new StreamReader(fs))
             {
                 string barcode_data = sr.ReadToEnd().Replace("\r\n", ",");
                 string[] Allbarcodes = barcode_data.Split(',');

                 for (int i = 0; i < Allbarcodes.Length; i++)
                 {
                     long sumOfnum = Summation(Convert.ToInt64(Allbarcodes[i]));
                     barcodeList.Add(sumOfnum);
                 }
             }
      }

推荐答案

听起来像数据问题,这些解决问题会停止错误,但可能会污染结果。你需要找出Allbarcodes中出错的地方[i]



1.使用TryParse,如果失败替换为0

Sound like a data issue, these work around will stop the error but it might pollute the results. You need to find out what when wrong in Allbarcodes[i]

1. Use TryParse, if failed substitute with 0
long sumOfnum = 0;
Int64.TryParse(Allbarcodes[i], out sumOfnum);
barcodeList.Add(sumOfnum);



2.在转换前检查Allbarcodes [i]是否为空


2.check if Allbarcodes[i] is empty before converting

if (!string.IsNullOrEmpty(Allbarcodes[i]) )
{
    long sumOfnum = Summation(Convert.ToInt64(Allbarcodes[i]));
    barcodeList.Add(sumOfnum);
}


这篇关于如何解决错误“输入字符串格式不正确”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆