我想制作流编写器功能,我可以多次写数字,并在程序结束时显示这些数字的总和。我怎么能编码这个东西?
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();
}
答案 0 :(得分:0)
您希望在代码中更改一些内容。 Speficially:
WriteLine
代替Write
。Convert.ToString
方法。try
中的finally
方法将代码写入StreamWriter.Close()
/ finally
块中的流编写器。否则,如果发生错误,不保证关闭您的文件。float
。请改用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();
}