将String转换为int [英] Converting String to int
问题描述
我很沮丧.我以为这样会更容易.
我以前使用过此代码....实际上我只是将其剪切并粘贴到
我的新代码.但是,数组的大小要大得多,为1000,10000,100000,并且要从一个文件中读取,该文件最多可以接受300,000的随机数.现在我的代码不起作用.
这是一段代码...
Im frustrated. I thought this would be easier.
I have used this code before....actually I just cut and pasted it into
my new code. However the array sizes is much larger 1000,10000,100000 and reading from a a file that accept random numbers of up to 300,000. Now my code will not work.
This is the piece of code...
<prelang> while ((number = s.ReadLine()) != null)
{
array[item] = Convert.ToInt32(number);
item++;
}</prelang>
我收到输入格式不正确的错误.有趣的是,我将代码分为2个不同的文件,并且可以正常工作.我不知道为什么.这些数字很大,是吗?
谢谢
:confused:
I am getting the error that input was not in correct format. The funny thing is I separated the code into 2 different files and it worked. I cant figure out why this is. These are very large numbers, could that be it?
thanks
:confused:
推荐答案
Tanacia,
1您可以在拥有更多控制权的地方使用int.Parse(..)
或int.TryParse(..)
.
2您可以发布引发异常的number的值吗?
干杯,
Avi
Tanacia,
1 you may useint.Parse(..)
orint.TryParse(..)
where you have more control.
2 Can you publish the value of number that throws an exception?
Cheers,
Avi
尝试一下:
Try this:
int LineNo = 0;
while ((number = s.ReadLine()) != null)
{
lineNo++;
int n = 0;
bool didConvert = int.TryParse(number, n);
if(didConvert)
{
array[item] = n;
item++;
}
else
Console.WriteLine("Line {1}: Could not convert {0} to an int!", number, lineNo);
}
干杯
Manfred
Cheers
Manfred
将while
语句写为
while (!string.IsNullOrEmpty(number = s.ReadLine()))
可能更好:) BTW
Hi, write thewhile
statement as
while (!string.IsNullOrEmpty(number = s.ReadLine()))
may be better :) BTW
这篇关于将String转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!