我是C#的新手。我一直在尝试读取缺少数据的数据集。在阅读标题后,我使用以下方法读取文件的其余部分:
List<int> idList = new List<int>();
List<int[]> valList = new List<int[]>();
string line = sr.ReadLine();
while (line != null)
{
string[] lineParts = line.Split(delimiters);
int id = Convert.ToInt32(lineParts[0]);
idList.Add(id);
int[] vals = new int[numTests];
for (int i = 0; i < numTests; i++)
{
vals[i] = Convert.ToInt32(lineParts[i + 1]);
}
valList.Add(vals);
line = sr.ReadLine();
}
childIDs = idList.ToArray();
int[][] values = valList.ToArray();
当我运行它时,我收到错误消息“输入字符串格式不正确”。我无法弄清楚如何读取丢失的数据。有什么建议?感谢
答案 0 :(得分:0)
“输入字符串格式不正确”表示您正在尝试从无意义的字符串中解析int。
例如:
Convert.ToInt32("the letter q"); // this will throw that exception.
答案 1 :(得分:0)
您可以使用可空整数来跟踪是否缺少数据。另外,请考虑使用int.TryParse而不是Convert.ToInt32来避免InvalidFormatException。例如:
List<int> idList = new List<int>();
List<int?[]> valList = new List<int?[]>();
string line;
while (null != (line = sr.ReadLine()))
{
string[] lineParts = line.Split(delimiters);
int id = Convert.ToInt32(lineParts[0]);
idList.Add(id);
int?[] vals = new int?[numTests];
for (int i = 0; i < numTests; i++)
{
int parsed;
if (!int.TryParse(lineParts[i + 1], out parsed))
vals[i] = null;
else
vals[i] = parsed;
}
valList.Add(vals);
line = sr.ReadLine();
}
childIDs = idList.ToArray();
var values = valList.ToArray();