i want to make stream writer function where i can write numbers several times and at the end of the program show me sum of those numbers. how i can code this thing?
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();
}
There are a couple of things you would want to change in your code. Speficially:
WriteLine
instead of Write
.Convert.ToString
method.try
/finally
block, with the StreamWriter.Close()
method in the finally
. Otherwise your file is not guaranteed to be closed in the event of an error.float
. Use decimal
instead, which is optimized for this purpose (as opposed to float
which is for scientific calculations).This code should give you a head start at the issue. It's up to you to complete it and organize it into methods, classes etc., depending on your specific requirements:
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();
}