我试图在21天内使用Sams Teach Yourself C#来学习C#的基础知识。
我通过从第1天类型和运行部分逐行复制来创建此程序。它编译得很好,但是当你运行它时会出现这个错误:“输入字符串的格式不正确”。
我正在从控制台运行程序。
我正在使用Visual Studio 2010 Express编辑器。
我复制的代码是:
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.");
}
}
}
}
}
答案 0 :(得分: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开始。第二个语句的右括号是方括号而不是卷曲括号。
另一个提示:在后一种情况下,您无需在.ToString()
上调用ctr
,除非您想明确指定文化。
答案 1 :(得分:0)
很少有事情需要注意:
OutFile.WriteLine("{1}: {2}", ctr.ToString().PadLeft(3, '1'), line);
索引基于0,因此它应为OutFile.WriteLine("{0}: {1}"...
Console.Write("..{1]..", ctr.ToString());
这里有拼写错误! (我希望!),再次它应该是0而不是1。