4

我必须为我正在学习的计算机课程编写一个控制台应用程序。该程序使用 StreamReader 从文件中读取文本,将字符串拆分为单个单词并将它们保存在 String 数组中,然后向后打印单词。

只要文件中有回车,文件就会停止读取文本。谁能帮我解决这个问题?

这是主程序:

using System;
using System.IO;
using System.Text.RegularExpressions;

namespace Assignment2
{
    class Program
    {
        public String[] chop(String input)
        {
            input = Regex.Replace(input, @"\s+", " ");
            input = input.Trim();

            char[] stringSeparators = {' ', '\n', '\r'};
            String[] words = input.Split(stringSeparators);

            return words;
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            StreamReader sr = new StreamReader("input.txt");
            String line = sr.ReadLine();

            String[] splitWords = p.chop(line);

            for (int i = 1; i <= splitWords.Length; i++)
            {
                Console.WriteLine(splitWords[splitWords.Length - i]);
            }

            Console.ReadLine();

        }
    }
}

这是文件“input.txt”:

This is the file you can use to 
provide input to your program and later on open it inside your program to process the input.
4

3 回答 3

3

您可以使用StreamReader.ReadToEnd而不是StreamReader.ReadLine.

// Cange this:
// StreamReader sr = new StreamReader("input.txt");
// String line = sr.ReadLine();

string line;
using (StreamReader sr = new StreamReader("input.txt"))
{
    line = sr.ReadToEnd();
}

添加using块将确保输入文件也正确关闭。

另一种选择就是使用:

string line = File.ReadAllText("input.txt"); // Read the text in one line

ReadLine从文件中读取一行,并去掉尾随的回车符和换行符。

ReadToEnd会将整个文件作为单个字符串读取,并保留这些字符,从而使您的chop方法可以按写入方式工作。

于 2013-08-06T17:12:30.487 回答
3

你只是在读一行。您需要阅读所有行直到文件结束。以下应该有效:

    String line = String.Empty;
    using (StreamReader sr = new StreamReader("input.txt"))
    {
        while (!sr.EndOfStream)
        {
            line += sr.ReadLine();
        }
    }
于 2013-08-06T17:19:26.327 回答
2

问题是您正在调用ReadLine()的正是这样做的,它读取直到遇到回车(您必须在循环中调用它)。

通常,如果您想逐行读取文件,StreamReader实现看起来更像这样(来自 msdn);

        using (StreamReader sr = new StreamReader("TestFile.txt")) 
        {
            string line;
            // Read and display lines from the file until the end of  
            // the file is reached. 
            while ((line = sr.ReadLine()) != null) 
            {
                Console.WriteLine(line);
            }
        }

while 循环中的条件确保您将读取到文件末尾,因为如果没有可读取的内容ReadLine将返回。null

另一种选择是使用File.ReadAllLines(MyPath)它将返回一个字符串数组,每个元素是文件中的一行。举一个更完整的例子;

  string[] lines = File.ReadAllLines(MyFilePath);
  foreach(string line in lines)
  {
        string[] words = line.Split(' ').Reverse();
        Console.WriteLine(String.Join(" ", words));
  }

这三行代码执行以下操作;将整个文件读入一个字符串数组,其中每个元素都是一行。循环遍历该数组,在每一行上,我们将其拆分为单词并颠倒它们的顺序。然后我将所有单词与它们之间的空格重新连接在一起并将其打印到控制台。如果您希望整个文件以相反的顺序开始,那么您需要从最后一行而不是第一行开始,我将把这个细节留给您。

于 2013-08-06T17:12:16.127 回答