C# 试图写入数组,但结果为“0”;System32 Int[]”;
我正在读取的文本文件中有数字 返回的是C# 试图写入数组,但结果为“0”;System32 Int[]”;,c#,C#,我正在读取的文本文件中有数字 返回的是System32 Int[],而不是我想看到的数字。我做错了什么 static void Main(string[] args) { StreamReader fromFile = new StreamReader("test.txt"); int[] numbers = gatherNumbers(fromFile); Console.WriteLine("Files from test.txt has been gathered...
System32 Int[]
,而不是我想看到的数字。我做错了什么
static void Main(string[] args)
{
StreamReader fromFile = new StreamReader("test.txt");
int[] numbers = gatherNumbers(fromFile);
Console.WriteLine("Files from test.txt has been gathered...");
string textFile = userInput("Enter the filename that you wish to store the result in: ");
StreamWriter tillFil = new StreamWriter(textFile);
tillFil.WriteLine("Summa " + numbers);
Console.WriteLine("Summa " + numbers);
tillFil.Close();
Console.ReadLine();
}
private static int[] gatherNumbers(StreamReader fromFile)
{
List<int> listan = new List<int>();
string rad = fromFile.ReadLine();
while (rad != null)
{
int tal = Convert.ToInt32(rad);
listan.Add(tal);
rad = fromFile.ReadLine();
}
return listan.ToArray();
}
private static string userInput(string nameOfTextFile)
{
Console.WriteLine(nameOfTextFile);
string answer = Console.ReadLine();
return answer;
}
static void Main(字符串[]args)
{
StreamReader fromFile=newstreamreader(“test.txt”);
int[]number=gatherNumbers(fromFile);
WriteLine(“已收集test.txt中的文件…”);
string textFile=userInput(“输入要存储结果的文件名:”);
StreamWriter tillFil=新的StreamWriter(文本文件);
tillFil.WriteLine(“Summa”+数字);
控制台写入线(“Summa”+数字);
tillFil.Close();
Console.ReadLine();
}
私有静态int[]GatherNumber(StreamReader fromFile)
{
List listan=新列表();
字符串rad=fromFile.ReadLine();
while(rad!=null)
{
int tal=转换为32(rad);
添加(tal);
rad=fromFile.ReadLine();
}
返回listan.ToArray();
}
私有静态字符串userInput(字符串名为TextFile)
{
Console.WriteLine(文本文件名);
字符串answer=Console.ReadLine();
返回答案;
}
System.Array不会覆盖ToString
——因此您会得到打印类型名称的默认行为。这与做以下事情没有什么不同:
// namespace X { class Foo {} }
Foo f = new Foo();
Console.WriteLine(f); // Prints "X.Foo"
// http://ideone.com/YyfIqX
Console.WriteLine(new object[0]); // Prints System.Object[]
Console.WriteLine(new int[0]); // Prints System.Int32[]
Console.WriteLine(new string[0]); // Prints System.String[]
如果你想要一个逗号分隔的列表,你需要自己去做
var commaSeparated = String.Join(", ", numbers);
将字符串与某个其他类型的实例连接在一起时,编译器会发出如下代码:
var tempValue = "This is a string" + thisIsSomeVariable.ToString();
因此,您的代码更准确地表示为:
Console.WriteLine("Summa " + numbers.ToString());
在这种情况下,数字是什么?它是一个整数数组,不是字符串或基元类型。非原语类型的ToString
的默认实现只是打印出类型名,在本例中为
System.Int32[]
或整数数组。你想做的是
Console.WriteLine("Summa " + string.Join(" ", numbers));
联接将对数组中的每个int调用
ToString
,然后将它们与每个int之间的空格组合起来。是否显示错误?你能给我们一些文件中的输入吗?你正在试图写一个数组。不要那样做。有关解决方案,请参见。您需要打印数组的内容。调用ToString()
(通过执行tillFil.WriteLine(“Summa”+数字);
)对您无效。您不必对数组进行选择。@will:我明白了,