0

How do i input integers from a file into a vector3 or a int variable? This is my code what works for only string

using (var enviromentPos = new FileStream("enviromentPos.txt", FileMode.OpenOrCreate))
{
  using(var input = new StreamReader(enviromentPos))
  {
    int line = "";

    while ((line = input.ReadLine()) != null)
    {
    }
  }
}
4

2 回答 2

0
String line="";
List<int> foo = new List<int>()    
while ((line = input.ReadLine()) != null)
{
    int i=0;
    if(int.TryParse(line,out i)) foo.Add(i);
}

将逐行读取并将所有包含 int-parseable 内容的行添加到列表中作为解析的 int 值

于 2013-04-20T21:02:29.967 回答
0

获得读取输入的代码后:

String line = null;
var input = new List<int>();
while ((line = file.ReadLine()) != null)
{
    int i = 0;
    if( int.TryParse(line,out i))
    {
       input.Add(i);
    }
}

您可以在之后处理该列表:

var vectors = new List<Vector3>();
for (int index = 0; index < input.Count; index += 3)
{
    vectors.Add(new Vector3(input[index], input[index+1], input[index+2]);
}

您需要通过截断或填充来确保输入是三的倍数。

或者您可以在阅读时处理输入,但是您需要一个计数器,以便您可以vectors.Add每隔三个从文件中读取的值执行一次代码:

String line = null;
var input = new List<int>();
int count = 0;
var vectors = new List<Vector3>();
while ((line = file.ReadLine()) != null)
{
    int i = 0;
    if( int.TryParse(line,out i))
    {
       input.Add(i);
       count++;
       if (count % 3 == 0)
       {
          vectors.Add(new Vector3(input[count-2], input[count-1], input[count]);
       }
    }
}
于 2013-04-20T21:21:12.617 回答