Exercise
Writing to a text file
Objetive
Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt"
Example Code
// Importing necessary namespaces to handle input/output functionalities
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Prompt to inform the user about the program's functionality
Console.WriteLine("Enter sentences (press Enter on an empty line to finish):");
// Initializing a StreamWriter to write data to "sentences.txt"
using (StreamWriter writer = new StreamWriter("sentences.txt"))
{
// Infinite loop to collect sentences from the user
while (true)
{
// Reading the user's input sentence
string sentence = Console.ReadLine();
// Checking if the input is empty to terminate input collection
if (string.IsNullOrEmpty(sentence))
break; // Exiting the loop if no sentence is entered
// Writing the user's sentence to the file
writer.WriteLine(sentence);
}
}
// Informing the user that the sentences have been saved to the file
Console.WriteLine("Sentences saved to sentences.txt.");
}
}