3

私は21日間でSamsTeachYourself C#を使用してC#の基本を学ぼうとしています。

このプログラムは、1日目のタイプと実行セクションから1行ずつコピーして作成しました。正常にコンパイルされますが、実行すると、「入力文字列が正しい形式ではありませんでした」というエラーが発生します。

コンソールからプログラムを実行しています。

Visual Studio2010Expressエディターを使用しています。

私がコピーしたコードは次のとおりです。

using System;
using System.IO;

/// <summary>
/// Class to number a listing. Assumes fewer than 1000 lines.
/// </summary>

class NumberIT
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>

    public static void Main(string[] args)
    {
        // check to see if a file name was included on the command line.

        if (args.Length <= 0)
        {
            Console.WriteLine("\nYou need to include a filename.");
        }
        else
        {
            // declare objects for connecting to files...
            StreamReader InFile = null;
            StreamWriter OutFile = null;

            try
            {
                // Open file name included on command line...
                InFile = File.OpenText(args[0]);

                // Create the output file...
                OutFile = File.CreateText("outfile.txt");
                Console.Write("\nNumbering...");

                // Read first line of the file...
                string line = InFile.ReadLine();
                int ctr = 1;

                // loop through the file as long as not at the end...
                while (line != null)
                {
                    OutFile.WriteLine("{1}: {2}", ctr.ToString().PadLeft(3, '1'), line);
                    Console.Write("..{1]..", ctr.ToString());
                    ctr++;
                    line = InFile.ReadLine();
                }
            }

            catch (System.IO.FileNotFoundException)
            {
                Console.WriteLine("Could not find the file {0}", args[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
            finally
            {
                if (InFile != null)
                {
                    // Close the files
                    InFile.Close();
                    OutFile.Close();
                    Console.WriteLine("...Done.");
                }
            }
        }
    }
}
4

2 に答える 2

2

ここでの原因は、OutFile.WriteLineステートメントとConsole.Writeステートメントです。

OutFile.WriteLine("{1}: {2}", ctr.ToString().PadLeft(3, '1'), line);
Console.Write("..{1]..", ctr.ToString());

それは読むべきです:

OutFile.WriteLine("{0}: {1}", ctr.ToString().PadLeft(3, '1'), line);
Console.Write("..{0}..", ctr.ToString());

フォーマット文字列のプレースホルダーは0から始まることに注意してください。2番目のステートメントの閉じ括弧は、中括弧ではなく角括弧でした。

もう1つのヒント:カルチャを明示的に指定する場合を除いて、後者の場合は.ToString()呼び出す必要はありません。ctr

于 2012-09-03T10:34:13.773 に答える
0

注意すべき点はほとんどありません。

OutFile.WriteLine("{1}: {2}", ctr.ToString().PadLeft(3, '1'), line);

インデックスは0ベースなので、OutFile.WriteLine("{0}: {1}"...

Console.Write("..{1]..", ctr.ToString());

ここにタイプミスがあります!(私は願っています!)そして再びそれは1ではなく0でなければなりません。

于 2012-09-03T10:35:29.437 に答える