C# 流编写器:如何在新行上写数字?

  • 本文关键字:新行 数字 c# streamwriter
  • 更新时间 :
  • 英文 :


我想使流编写器函数,我可以在其中多次写入数字,并在程序结束时显示这些数字的总和。 我怎么能编码这个东西?

public static void bought(float a)
{
StreamWriter SW = new StreamWriter(@"C:UsersETNsourcereposApple-storeApple-storebuy.txt");
SW.Write(a);
SW.Close();
}

您需要在代码中更改一些内容。具体而言:

  • 您正在打开一个流编写器,写入一个值并将其关闭。除非已经有要写入的值列表,否则通常打开和关闭流编写器一次,然后多次调用它。
  • 如果要在写入的值后添加新行,请使用WriteLine而不是Write
  • 将数值写入文本文件时,它们将转换为依赖于区域性的文本。请注意,默认值是系统的区域性。如果从具有不同区域性的其他计算机读取文件,则文件可能无法读取。因此,您应该始终提供特定的区域性。为此,请检查Convert.ToString方法。
  • 您应该将写入流编写器的代码包含在try/finally块中,并在finally中使用StreamWriter.Close()方法。否则,不保证在发生错误时关闭文件。
  • 不建议将货币信息(如价格或账户余额(存储为float。请改用decimal,它是为此目的而优化的(而不是用于科学计算的float(。

此代码应该可以让您抢占先机。由您来完成它并将其组织成方法、类等,具体取决于您的特定要求:

StreamWriter writer = new StreamWriter(@"C:UsersETNsourcereposApple-storeApple-storebuy.txt");
try {
while (true) {
decimal price:
//Your code that determines the price goes here
string priceText = Convert.ToString(price, CultureInfo.InvariantCulture);
writer.WriteLine(priceText);
bool shouldContinue;
//Your code that determines whether there are more values to be written goes here
if (!shouldContinue) {
break;
}
}
writer.Flush();
}
finally {
writer.Close();
}

相关内容

最新更新