I have written a console application that in itself is working as I would like it to. It's main output works great in console. But the results inside the loop I want written to a text file. I have used StreamWriter to attempt this and although I receive no errors on compilation or running, the file in my C: drive remains blank. Can anyone spot any stupid or quick things I have missed?
If you can help, thank you in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test2
{
class Program
{
static void Main(string[] args)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\Test.txt");
double z = 0;
double x = 1;
double y = 1;
Console.WriteLine("How many lines should be written to the file?");
Console.WriteLine();
z = double.Parse(System.Console.ReadLine());
Console.WriteLine("Writing " + z + "lines to file!");
Console.WriteLine();
while (z > 0)
{
y = Math.Pow(x, 2);
Console.WriteLine(x + ", " + y*10);
file.WriteLine(x + ", " + y*10);
z = z - 1;
x = x + 1;
}
Console.WriteLine();
Console.WriteLine("**Generation Complete**");
Console.WriteLine();
Console.WriteLine("-------------------------------");
Console.WriteLine();
Console.WriteLine("**Writing to file successful**");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
file.Close();
}
}
}
I've had issues similar to this before. If I recall correctly, the solution came down to wrapping the StreamWriter in a using block, rather than creating it and then trying to close it, e.g.
static void Main(string[] args)
{
using (var file = new System.IO.StreamWriter("c:\\Test.txt"))
{
double z = 0;
double x = 1;
double y = 1;
Console.WriteLine("How many lines should be written to the file?");
Console.WriteLine();
z = double.Parse(System.Console.ReadLine());
Console.WriteLine("Writing " + z + "lines to file!");
Console.WriteLine();
while (z > 0)
{
y = Math.Pow(x, 2);
Console.WriteLine(x + ", " + y*10);
file.WriteLine(x + ", " + y*10);
z = z - 1;
x = x + 1;
}
Console.WriteLine();
Console.WriteLine("**Generation Complete**");
Console.WriteLine();
Console.WriteLine("-------------------------------");
Console.WriteLine();
Console.WriteLine("**Writing to file successful**");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Use the using statament for everything that implements IDisposable like the StreamWriter. This will ensure that unmanaged resources are disposed (even on error). It'll also flush the stream if it's AutoFlush property is false(default).
using(var file = new System.IO.StreamWriter("c:\\Test.txt"))
{
// ...
file.WriteLine(x + ", " + y*10);
// rest of code here ...
}
Does Stream.Dispose always call Stream.Close (and Stream.Flush)
When I run that code, I see an exception:
Unhandled Exception: System.UnauthorizedAccessException:
Access to the path 'c:\Test.txt' is denied.
It's not clear how you're running this, but if it's configured as a console app and you run it from a console window so you'll definitely see any exceptions, I suspect you'll see the same thing.
Try changing it to write to somewhere you definitely have access to - and also try to work out why you didn't see the exception before.
Additionally it would definitely be better to use a using statement as other answers have shown - but that wouldn't explain a clean run (no exceptions) without the file being created.
Related
I'm making a simple poll/survey to check where user can go to work. I went with yes or no answers. I made a point counter, so it can check user information if he answered yes then add one point. I want to make a function that displays a question and check user input instead of writing same do while loop for each question. I made an array for collecting "user points". But, the problem is that since program is jumping to loop and adding +1 point it just can't return a value to this "point array". This value is somewhere else in memory but not in array. This results to not properly working summary. It just shows everywhere 0 points to each possible work. What I've made wrong or what can I make to make it working properly?
Here's my code (I probably messed up formatting braces by copy/paste):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Survey
{
class Program
{
static void Main(string[] args)
{
//here's my Question Bank
ArrayList QuestionList = new ArrayList();
QuestionList.Add("1. Question");
QuestionList.Add("2. ...");
QuestionList.Add("3. ...");
QuestionList.Add("4. ...");
QuestionList.Add("5. ...");
QuestionList.Add("6. ...");
QuestionList.Add("7. ...");
QuestionList.Add("8. ...");
QuestionList.Add("9. ...");
QuestionList.Add("10. ...");
//here's my work list.
ArrayList WorkList = new ArrayList();
WorkList.Add("IT");
WorkList.Add("Architect");
WorkList.Add("Politician");
WorkList.Add("Driver");
WorkList.Add("Designer");
//here's an array, where I want to hold "points". The higher points the more probably user will get suggestion where to work.
int[] Work;
Work = new int[5] { 0, 0, 0, 0, 0 };
Console.WriteLine("Hi. Say 'y' if you agree or 'n' if not.");
displayQuestion(QuestionList[0], Work[0]);
displayQuestion(QuestionList[1], Work[1]);
displayQuestion(QuestionList[2], Work[2]);
displayQuestion(QuestionList[3], Work[3]);
displayQuestion(QuestionList[4], Work[4]);
displayQuestion(QuestionList[5], Work[4]);
displayQuestion(QuestionList[6], Work[1]);
displayQuestion(QuestionList[7], Work[2]);
displayQuestion(QuestionList[8], Work[0]);
displayQuestion(QuestionList[9], Work[3]);
// here's calculating maximum points
int max;
max = Work[0];
for (int i=0; i<5; i++)
{
if (Work[i] > max)
max = Work[i];
}
for (int i = 0; i < 5; i++)
{
if(Work[i]==max)
Console.WriteLine("You can work as: " + WorkList[i]);
}
//Summary
Console.WriteLine("Points as: " + WorkList[0] + " = " + Work[0]);
Console.WriteLine("Points as: " + WorkList[1] + " = " + Work[1]);
Console.WriteLine("Points as: " + WorkList[2] + " = " + Work[2]);
Console.WriteLine("Points as: " + WorkList[3] + " = " + Work[3]);
Console.WriteLine("Points as: " + WorkList[4] + " = " + Work[4]);
Console.ReadLine();
}
//here's the PROBLEM (I think)
public static int displayQuestion(object whichQuestion, int WorkPoints)
{
string answer;
do
{
Console.WriteLine(whichQuestion);
answer = Console.ReadLine();
if (answer == "y")
{
WorkPoints++;
}
} while (answer != "y" && answer != "y");
return WorkPoints;
}
}
}
actually you're assigning the new score to the return value of the displayQuestion Method and not using it.
public static int displayQuestion(object whichQuestion, int WorkPoints)
so a possible approach is tu use the ref keyword as Samvel said or assign the return value of the method to work[i]:
Work[0] = displayQuestion(QuestionList[0], Work[0]);
Change the function to the following:
public static int displayQuestion(object whichQuestion)
{
string answer;
int WorkPoints = 0;
do
{
Console.WriteLine(whichQuestion);
answer = Console.ReadLine();
if (answer == "y")
{
WorkPoints++;
}
} while (answer != "y" && answer != "n");
return WorkPoints;
}
}
and then use it this way:
Work[0] += displayQuestion(QuestionList[0]);
I wrote a basic number guessing game from C#. It seems to return the 3rd option ("Wrong choice! Please try again.") every time no matter what var c is chosen by the user. I was trying with characters (s instead of 1 and w instead of 2 etc with c as a string) but it gave the same results. Not sure where it's going bad.
using System;
namespace Challanges
{
class Program
{
static int guess = 500;
static int low = 1;
static int high = 1000;
static bool cont = false;
static void Guess() //guesses and adjusts variables according to input.
{
int c;
Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
c = Convert.ToInt32(Console.Read());
if (c == 1)
{
high = 500;
guess = low + high / 2;
}
else if (c == 2)
{
low = 500;
guess = low + high / 2;
}
else if (c == 3)
{
Console.WriteLine("Congratulations!! We found your number!");
cont = true;
}
else
{
Console.WriteLine("Wrong choice! Please try again.");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
Console.ReadKey();
Console.WriteLine("Think of a number");
if(cont == false)
{
Guess();
} else
{
Console.ReadKey();
}
}
}
}
As mentioned in the comments before, Console.Read() returns a character code. The character code for the number 1 is 49, thus your conditions fail and the else block is executed.
What you wanted to do was use Console.ReadLine()which returns a string instead of character codes. If you cast that string into an Int32 you should be able to evaluate your conditions correctly.
So line #59 has what i can only describe as a wackadoodle error (if i'm understanding my code correctly that is) which is that if you leave the return line with Console.ReadLine() the file will run, if you change it to Console.Read()), the file will produce errors when running. The odd thing is that it shouldn't run because I don't call the functions or do the actual console.writes, etc. So i was hoping someone out there could help me to understand this and either confirm that i am correct in thinking i've got some wacky code OR that my understanding of how the code runs is incorrect.
Code that produces the error:
public string GetStr(String StrVar)//note - using strings here
{
Console.Write(StrVar);return Console.ReadLine().ToLower().Trim();
}
If the line return Console.ReadLine() is changed to return Console.Read(), the file errors - but the file should really run regardless as i don't actually call anything - it seems like the string vars are somehow self-writing to the console if i understand what is happening.
Full Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace a015_mealCalculator
{
class Program
{
public void Play()
{
//DisplayChek("DisplayChek!");
do //do while loop
{
DisplayStr(">>>-- Meal Calculator v1.3 --<<< \n\n\n");//Welcome
//ask info
String fName = GetStr("Enter your FIRST NAME here: ");
String lName = GetStr("Enter your LAST NAME here: ");
String rName = GetStr("Enter the NAME of the RESTURANT you are dinning at here: ");
String wholeName = fName + " " + lName;
double mealCost = GetDouble("How much was your meal " + fName + "?");
String mealGreeting = "\n" + wholeName + ", your meal at " + rName + " was:";
//process math
double tax = mealCost / 8;
double tip = mealCost % 18;
double totalCost = mealCost + tip + tax;
tax = Math.Round(tax, 2);//trim decimals
tip = Math.Round(tip, 2);//trim decimals
totalCost = Math.Round(totalCost, 2);
//Announce results
Console.WriteLine("\nMeal: " + mealCost);
Console.WriteLine(mealGreeting);
Console.WriteLine("Meal: $" + mealCost);
Console.WriteLine("Tax: $" + tax);
Console.WriteLine("Tip: $" + tip);
Console.WriteLine("Total: $" + totalCost);
} while (PlayAgain());
DisplayStr("Enjoy Your Meal!"); //Salutation
}
//MaxBox
public void DisplayChek(String StringNameIs)
{ Console.WriteLine("I am in " + StringNameIs); }//Where are we?
public void DisplayStr(String StrTxt)
{ Console.WriteLine(StrTxt); }
public void DisplayRs()
{ Console.Write("\n\n"); }
public string GetStr(String StrVar)//note - using strings here
{ Console.Write(StrVar);return Console.ReadLine().ToLower().Trim(); }
public double GetDouble(String doubleRequest)// We take in a STRING but we return a DOUBLE
{
Console.WriteLine(doubleRequest + ": "); // HERE we use the STRING to ask for the DOULBE
return double.Parse(Console.ReadLine()); //HERE we RETURN the DOUBLE asked for!
}
public Boolean PlayAgain()
{
Console.Write("\n\nDo you want to play again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
static void Main(string[] args)
{
Program MealCalculator = new Program();
MealCalculator.Play();
//Play keeps file open
//Console.Read();
}
}
}
Console.Read() returns an integer, ReadLine() returns a string.
The ReadLine method, or the KeyAvailable property and ReadKey method are preferable to using the Read method.
If you look at the documentation of both methods: Console.Read() returns the character code of the next character read from the console stream as an integer, whilst Console.ReadLine() returns a line as a string. double.Parse accepts a string parameter, so in the first case there is a type mismatch.
This will not compile as Console.Read() returns an int. You cannot perform .ToLower() on an int.
How do I arrange the numbers next to each other instead of on top of each other?
I tried implementing \t but it gives me an error or doesn't do anything at all.
int[] anzFeldElemente = new int[10];
Random wuerfel = new Random();
for (int i = 0; i < anzFeldElemente.Length; i++)
{
anzFeldElemente[i] = wuerfel.Next(0, 100);
}
Array.Sort(anzFeldElemente);
foreach (int i in anzFeldElemente)
{
Console.WriteLine(i "\t");
}
Console.ReadLine();
Also, is it possible to draw a field similar to Microsoft Excel in a console app? Is there a function to draw one?
Thanks in advance.
Using Console.WriteLine will force it to move to the next line every time you iterate. As recommended by lazyberezovsky use the Console.Write instead. Remember to include a white space to divide up the elements using +", "
As the name implies, Console.WriteLine writes a line.
Instead of
Console.WriteLine(i "\t");
Try
Console.Write(i + "\t");
Or
Console.Write("{0}\t", i);
It should be like this:
Console.Write(i + "\t");
i have created a marksheet program in c# 2005, its working fine it is taking input and showing the output by using the below code. now if i want that the output of this program is also copied in a new file located in my C or any drive. what should i do? i tried IO.StreamWriter but its not working.
using(System.IO.TextWriter writer = System.IO.File.CreateText(#"C:\1.txt"))
{
Console.WriteLine("\t\tMarksheet - Prislogix Public School");
Console.Write("\n\nStudent Name : " + name);
Console.Write("\nClass : " + cls);
Console.Write("\nRoll Number : " + roll);
Console.Write("\n\nSubject\t\tObtained Marks\t\tTotal Marks");
Console.Write("\n\nChemistry\t\t" + chem + "\t\t75");
Console.Write("\nEnglish\t\t\t" + eng + "\t\t100");
Console.Write("\nCalculus\t\t\t" + urd + "\t\t100");
Console.Write("\nDiscrete\t\t\t" + sin + "\t\t75");
Console.Write("\nMathematics\t\t" + mat + "\t\t100");
Console.Write("\nPhysics\t\t\t" + phy + "\t\t75");
Console.Write("\nComputer\t\t" + comp + "\t\t100");
Console.Write("\nMethods\t\t" + isl + "\t\t50");
float tot = chem + eng + urd + sin + mat + phy + comp + isl;
Console.Write("\n\n\t\t\tTotal Obtained Marks : " + tot + "\tOut Of 625");
float per;
per = (tot / 625) * 100;
Console.Write("\n\t\t\tPercentage : " + per + "%");
if (per < 49 && per > 40)
{
Console.Write("\n\t\t\tFAILED!");
}
if (per <= 59 && per >= 50)
{
Console.Write("\n\t\t\tGrade : C");
}
if (per <= 69 && per >= 60)
{
Console.Write("\n\t\t\tGrade : B");
}
if (per <= 79 && per >= 70)
{
Console.Write("\n\t\t\tGrade : A");
}
if (per <= 89 && per >= 80)
{
Console.Write("\n\t\t\tGrade : A+");
}
if (per <= 100 && per >= 90)
{
Console.Write("\n\t\t\tGrade : A-ONE");
}
}
}
Console.ReadLine();
StreamWriter does work. It's a shame you haven't shown us your attempt at using it.
The simplest way of creating a StreamWriter to write to a file is to use File.CreateText. Then you should be able to use StreamWriter.Write in the same way as Console.Write. Don't forget to use a using statement:
using (TextWriter writer = File.CreateText("..."))
{
// Write stuff here
}
That makes sure the writer will be disposed at the end of the using statement, which will flush and close the file.
If you want to write to both the console and the file, you may want a "tee" TextWriter which writes to two outputs... or you could just look at the file after running the program.
One thing to note: in Windows, the normal line ending is \r\n rather than just \n. If the problem was just that all the output looked like it was on one line in Notepad, that's probably the issue. Consider using WriteLine instead of Write, to write out the platform default line terminator at the end of the line.
If all of this fails, please tell us what's going wrong with rather more detail than "it's not working".
Change all calls to Console.Write so that they write to a StringBuilder instance instead. After the printing is done you can do the following:
Console.Write(stringBuilder.ToString());
System.IO.File.WriteAllText("your path here", stringBuilder.ToString());
This will probably be the easiest fix. It will still write the output to the Console, but it will also write to the file you want.