C# 输入字符串格式不正确错误
我正在努力学习C#的基础知识,使用Sams在21天内自学C# 我已经创建了这个程序,从第1天的类型和运行部分逐行复制它。它可以很好地编译,但当您运行它时,会出现以下错误:“输入字符串的格式不正确” 我正在从控制台运行程序 我正在使用VisualStudio2010Express编辑器 我复制的代码是:C# 输入字符串格式不正确错误,c#,C#,我正在努力学习C#的基础知识,使用Sams在21天内自学C# 我已经创建了这个程序,从第1天的类型和运行部分逐行复制它。它可以很好地编译,但当您运行它时,会出现以下错误:“输入字符串的格式不正确” 我正在从控制台运行程序 我正在使用VisualStudio2010Express编辑器 我复制的代码是: using System; using System.IO; /// <summary> /// Class to number a listing. Assumes fewer t
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.");
}
}
}
}
}
使用系统;
使用System.IO;
///
///类对列表进行编号。假设少于1000行。
///
类号
{
///
///应用程序的主要入口点。
///
公共静态void Main(字符串[]args)
{
//检查命令行中是否包含文件名。
如果(args.Length您的罪魁祸首是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开始。第二条语句上的右括号是方括号而不是花括号
另一个提示:在后一种情况下,您不需要在ctr
上调用.ToString()
,除非您想明确指定区域性。需要注意的几点:
OutFile.WriteLine("{1}: {2}", ctr.ToString().PadLeft(3, '1'), line);
索引是基于0的,因此它应该是OutFile.WriteLine(“{0}:{1}”)…
Console.Write("..{1]..", ctr.ToString());
这里有一个输入错误!(我希望!),而且它应该是0而不是1。如果您想链接字符串方法,比如PadLeft()
这里的WriteLine()
语句中的ToString()
,您需要调用
statement.@Gorpik是的,我指的是控制台。写下语句。我承认我可以更清楚一点。