gpt4 book ai didi

c# - 我的 StreamReader 只从我的 4 行文本文件中读取第二行和第四行

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:14 26 4
gpt4 key购买 nike

我有一个程序可以从文件中读取数据并使用该数据为图形创建节点。问题是,从一个 4 行的文件中,我的程序只创建了两个节点(一行应该创建一个节点)。文本文件如下所示:

A/0/0.7
C/1/0/0.1 0.4
B/1/0/0.6 0.8
D/2/2 1/0.6 0.7 0.1 0.2

节点数据的结构(它是一个贝叶斯网络):

节点名称/ parent 的数量/ parent 在文件中的索引/概率

using (StreamReader reader = new StreamReader(file))
{
while ((line = reader.ReadLine()) != null)
{
line = reader.ReadLine();
string name = "";
List<int> parents = new List<int>();
List<float> probs = new List<float>();
string[] splitLine = line.Split('/');
Console.WriteLine("splitLine array: ");
foreach (string item in splitLine)
{
Console.WriteLine(item);
}
Console.WriteLine();
int index = 2;

name = splitLine[0];

if (splitLine.Length == 4)
{
string[] temp = splitLine[2].Split(' ');
foreach (string item in temp)
parents.Add(Int32.Parse(item));
index = 3;
}

string[] temp1 = splitLine[index].Split(' ');
foreach (string item in temp1)
probs.Add(float.Parse(item, CultureInfo.InvariantCulture.NumberFormat));

Node newNode = new Node(name, parents, probs);
graph.Add(newNode);
}
}

如果调用节点构造函数,程序将打印新节点具有的数据。我希望它打印:

Created Node:
Name: A
Parents' indexes: 0
Probabilities: 0.7
Created Node:
Name: C
Parents' indexes: 0
Probabilities: 0.1 0.4
Created Node:
Name: B
Parents' indexes: 0
Probabilities: 0.6 0.8
Created Node:
Name: D
Parents' indexes: 2 1
Probabilities: 0.6 0.7 0.1 0.2

但是我得到:

Created Node:
Name: C
Parents' indexes: 0
Probabilities: 0.1 0.4
Created Node:
Name: D
Parents' indexes: 2 1
Probabilities: 0.6 0.7 0.1 0.2

最佳答案

你调用 reader.ReadLine() 两次:

while ((line = reader.ReadLine()) != null) // <-- First here
{
line = reader.ReadLine(); // <-- Again here

只需删除第二行 line = reader.ReadLine(),因此您的代码是:

...
while ((line = reader.ReadLine()) != null)
{
string name = "";
List<int> parents = new List<int>();
...

关于c# - 我的 StreamReader 只从我的 4 行文本文件中读取第二行和第四行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58451361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com