c#流作者:如何在新行上写数字?
我想让流编写器的功能,我可以写几次数字,并在程序结束时显示这些数字的总和。我怎么能给这东西编代码c#流作者:如何在新行上写数字?,c#,streamwriter,C#,Streamwriter,我想让流编写器的功能,我可以写几次数字,并在程序结束时显示这些数字的总和。我怎么能给这东西编代码 public static void bought(float a) { StreamWriter SW = new StreamWriter(@"C:\Users\ETN\source\repos\Apple-store\Apple-store\buy.txt"); SW.Write(a); SW.Close(); } 在代码中有
public static void bought(float a)
{
StreamWriter SW = new StreamWriter(@"C:\Users\ETN\source\repos\Apple-store\Apple-store\buy.txt");
SW.Write(a);
SW.Close();
}
在代码中有几件事需要更改。特别是:
- 您正在打开一个流编写器,编写一个值并关闭它。除非已经有了要写入的值列表,否则通常会打开和关闭流编写器一次,然后多次调用它
- 如果要在写入值后添加新行,请使用
而不是WriteLine
Write
- 将数值写入文本文件时,它们将根据区域性转换为文本。请注意,默认值是系统的区域性。如果从具有不同区域性的其他计算机读取该文件,则该文件可能无法读取。因此,您应该始终提供特定的文化。为此,请检查
方法Convert.ToString
- 您应该使用
中的finally
方法将写入流编写器的代码封装在StreamWriter.Close()
/try
块中。否则,不能保证在发生错误时关闭文件finally
- 不建议将货币信息(如价格或账户余额)存储为
。使用浮动
,这是为此目的而优化的(而不是用于科学计算的decimal
)float
StreamWriter writer = new StreamWriter(@"C:\Users\ETN\source\repos\Apple-store\Apple-store\buy.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();
}
首先,您可能需要将参数设置为数组或collectionhow?我不擅长流编写器功能,你能帮我吗?我不知道将使用多少数字欢迎使用堆栈溢出!你能提供一些背景吗?您想做什么(广义上)以及为什么?
新StreamWriter(@“…”,append:true)
和SW.WriteLine(a)
亲爱的Nick.McDermaid我搜索解决方案两天了,但我无法安排编写此代码。如果你能单独使用谷歌,stackoverflow根本不需要