Hope everyone is well,
I am a newb to C# and starting an online class soon however I have been doing my own thing and I am stuck with wanting to make a change to the below code
Console.Write("Input First Name: "); string firstName = Console.ReadLine();
Console.Write("Input Last Name: ");
string lastName = Console.ReadLine();
Console.Write("Input your Email: ");
string email = Console.ReadLine();
Console.Write("Input your D.O.B: ");
string dob = Console.ReadLine();
string details = $"Full detail is: {firstName} {lastName} {email} {dob}";
Console.WriteLine(details);
However, the result shows the details all in one line in command prompt, I would like to show the firstName, lastName, email and dob in seperate lines.
I would appriciate your advise/guide on this.
Thank you
CodePudding user response:
Use \n in your output string {firstName}\n{lastName}
etc.
CodePudding user response:
You can use "\n" in your String, like the following:
string details = $"Full detail is: {firstName}\n{lastName}\n{email}\n{dob}";
The "\n" indicates a line break. You can read more here about Character Escapes!
CodePudding user response:
Try with:
string details = $"Full detail is:\r\n{firstName}\r\n{lastName}\r\n{email}\r\n{dob}";
Console.WriteLine(details);
//You can also use Environment.NewLine as new line separator,
// but in this case it makes the output not very readable
//Or just:
Console.WriteLine("Full detail is:");
Console.WriteLine(firstName);
Console.WriteLine(lastName);
Console.WriteLine(email);
Console.WriteLine(dob);
Console.Write
won't add a new line at end of the output.
Console.WriteLine
does add a new line at the end of the ouput
CodePudding user response:
You can use \n
as a new line separator, however, it's recommended to use Environment.NewLine
which would give \r\n
in Windows, and \n
in Unix based environments. This would ensure cross-platform compatibility.
example :
string details = $"Full detail is: {firstName}{Environment.NewLine}{lastName}{Environment.NewLine}{email}{Environment.NewLine}{dob}";
CodePudding user response:
Everybody has been suggesting the \n
or {Environment.NewLine}
which is a very much correct way to doing what you asked but for the sake of educating you use the special character @
which serves as a verbatim identifier. E.g.
string lastName = "Bob";
string email = "[email protected]";
string dob = "12-07-2022";
string details = @$"Full detail is:
{lastName}
{email}
{dob}";
CodePudding user response:
You can try joining with Environment.NewLine
delimiter:
Console.WriteLine(
$"Full detail is: {string.Join(Environment.NewLine, firstName, lastName, email, dob)}");