4

受講しているコンピューター コース用のコンソール アプリケーションを作成する必要があります。このプログラムは、StreamReader を使用してファイルからテキストを読み取り、文字列を 1 つの単語に分割して文字列配列に保存し、単語を逆方向に出力します。

ファイルに改行があると、ファイルはテキストの読み取りを停止します。誰でもこれで私を助けることができますか?

主なプログラムは次のとおりです。

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

あなたは一行で読んでいるだけです。ファイルの最後まですべての行を読み取る必要があります。以下が機能するはずです。

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