Reputation: 211
I have write the following C# code to append a file. I need to store each data in a new line. But after entering the data I can see them in a single line.
How can I modify my code to get one input in one line.
static void Main(string[] args)
{
Console.WriteLine("Please enter the question:");
string question = Console.ReadLine();
File.AppendAllText("question.txt", question);
File.AppendAllText("question.txt", "\n");
Console.WriteLine("Please enter the term to solve");
string term = Console.ReadLine();
File.AppendAllText("question.txt", term);
}
Required output -
x+2=10
x
Output I got -
x+2=10x
Upvotes: 1
Views: 182
Reputation: 2420
Add + Environment.NewLine
after term
. You can concat string with +
(plus) "mystring" + " another String" + " my last string" = "mystring another String my last string".
static void Main(string[] args)
{
Console.WriteLine("Please enter the question:");
string question = Console.ReadLine();
File.AppendAllText("question.txt", question);
File.AppendAllText("question.txt", "\n");
Console.WriteLine("Please enter the term to solve");
string term = Console.ReadLine();
File.AppendAllText("question.txt", term + Environment.NewLine);
}
Upvotes: 3
Reputation: 437
The text viewer you are viewing the resulting file with likely expects a "carriage return"(\r) character with each "newline"(\n) character. Try changing the following line:
File.AppendAllText("question.txt", "\n");
To this:
File.AppendAllText("question.txt", "\r\n");
Upvotes: 1
Reputation: 13043
Why not to build a string and write it at once?
Console.WriteLine("Please enter the question:");
string question = Console.ReadLine();
Console.WriteLine("Please enter the term to solve");
question += Environment.NewLine + Console.ReadLine();
File.WriteAllText("question.txt", question );
Anyway, as C# application might be cross platform, /n
is not always a character for the new line, that is why it is better to use Environment.NewLine
instead
Upvotes: 2