我正在处理这个问题,无法让我的输出文件显示输入文件中按字母顺序排列的整个字符串。
我的输入文件是:(三行之间没有间距)
eafcd
FGHIJ
LK
输出文件是:(三行之间没有间距)
FGHIJ
LK
我认为问题出现在我的字母顺序排列方法中,但我似乎无法弄清楚为什么某些字符没有出现在输出文件中。
感谢您的帮助!
使用System; 使用System.IO;
命名空间TestFileIO { class fileFileIO { private static string foo;
static void Main(string[] args)
{
StreamWriter writer = null;
writer = new StreamWriter(@"C:\Files\OutputWrite2.txt");
Console.SetOut(writer);
Console.SetIn(new StreamReader(@"C:\Files\InputRead2.txt"));
string letters = Console.ReadLine();
foo = alphabetize(letters);
string line = foo;
while ((line = Console.ReadLine()) != null)
{
string newLine = line;
Console.WriteLine(newLine);
}
writer.Close();
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("Alphabetized all characters in requested file and wrote to output file.");
}
public static string alphabetize(string letters)
{
char[] line = letters.ToCharArray();
Array.Sort<char>(line);
return new string(line);
}
}
}
答案 0 :(得分:0)
while ((line = Console.ReadLine()) != null)
{
string newLine = line;
Console.WriteLine(newLine);
}
while条件中的Console.ReadLine()正在覆盖'line'变量的内容。这就是你错过输入文件第一行
的原因以下代码应满足您的要求。
static void Main(string[] args)
{
StreamWriter writer = null;
writer = new StreamWriter(@"D:\OutputWrite2.txt");
Console.SetOut(writer);
Console.SetIn(new StreamReader(@"D:\InputRead2.txt"));
string letters = Console.ReadLine();
while (letters != null)
{
var foo = alphabetize(letters);
string line = foo;
string newLine = line;
Console.WriteLine(newLine);
letters = Console.ReadLine();
}
writer.Close();
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("Alphabetized all characters in requested file and wrote to output file.");
}
public static string alphabetize(string letters)
{
char[] line = letters.ToCharArray();
Array.Sort<char>(line);
return new string(line);
}