我正在尝试编写一个小的 C# 程序,该程序从文本文件中读取数据并让您选择要打印的行。
出于某种原因,它只会打印第 1、3、5 行等
如果我将 int chooseLine = Convert.ToInt32(input);
更改为 int chooseLine = (int)Convert.ToInt64(input);
,那么它只打印偶数行。(0、2、4、6 等)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Steve
{
public static int count = 0;
public static String[] steveTalk;
public static void Main()
{
using (StreamReader r = new StreamReader("Steve.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
}
using (StreamReader sr = new StreamReader("Steve.txt"))
{
int i = 0;
steveTalk = new String[count];
String line;
while ((line = sr.ReadLine()) != null)
{
steveTalk[i] = line;
Console.WriteLine(steveTalk[i]);
i++;
}
}
while (true)
{
string input = Console.ReadLine();
int chooseLine = Convert.ToInt32(input);
try
{
Console.WriteLine(steveTalk[chooseLine]);
}
catch
{
Console.WriteLine("Error! Not a number or array index out of bounds");
}
Console.ReadLine();
}
}
}
有什么想法吗?
最佳答案
我想推荐 System.IO.File.ReadAllLines(filename)
方法。
string []lines=System.IO.File.ReadAllLines("Steve.txt");
string input ;
while ((input = Console.ReadLine()) != "end")
{
int chooseLine;
int.TryParse(input,out chooseLine);
if(chooseLine<lines.Length)
{
Console.WriteLine(lines[chooseLine]);
}
}
关于c# - 文本文件只读取奇数或偶数行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380585/