Home > database >  How to write statement in Console.WriteLine so that it prints in separate lines
How to write statement in Console.WriteLine so that it prints in separate lines

Time:01-04

I want to write a line in Console.WriteLine such that each part should be printed on separate line, temporary I have formatted with \r\n but it is difficult to manage, is there any good alternative ?

Console.WriteLine("\nWhat Operation you need to perform \r\nA-Addition: \r\nS-Subtraction: \r\nM-Multiplication: \r\nL-FindLargestElementInMatrix: \r\nS-FindSmallestElementInMatrix: \r\nDL-DisplayLowerTriangularMatrix: \r\nDU-DisplayUpperTriangularMatrix: \r\nT-FindTransposeOfMatrix: \r\nE-CheckIfTwoMatricesEqual: \r\nI-CheckIfTwoMatrixIsIdentityMatrix: \r\nS-SumOfDiagonalElementsOfMatrix: \r\nAR-SumOfEachRowOfMatrix: \r\nAC-SumOfEachColumnOfMatrix: \r\nIR-InterchangeRowsOfMatrix: \r\nIC-InterchangeColumnsOfMatrix: ");

I want to write a line in Console.WriteLine such that each part should be printed on separate line, temporary I have formatted with \r\n but it is difficult to manage, is there any way out ?

CodePudding user response:

The preferred option here is probably to call Console.WriteLine(...) once per line; the reason for this is so that the runtime/core-libs can make the determination about the most appropriate line-endings suitable for your display / stdout / etc - rather than the hard-coding present either explictly in strings "like\r\nthis" or in verbatim-string-literals or raw-string-literals (@"...includes line-breaks natively..." or """...includes line-breaks natively...""").

Console.WriteLine(value) is simply a short-cut to Console.Out.WriteLine(value), where Out can be redirected via Console.SetOut(TextWriter) - which means the output device could in theory be anything.

CodePudding user response:

In C# 11, you can use a raw string literal:

string output = """
    What Operation you need to perform
    A-Addition:
    S-Subtraction:
    ...
    """
Console.WriteLine(output);

In earlier versions of C# you can use a verbatim string. Note that we can't indent each line as we can with a raw string literal, as this will mean that the string printed to the console is also indented:

string output = @"What Operation you need to perform
A-Addition:
S-Subtraction:
...";
Console.WriteLine(output);

You can also just split your string into multiple strings, and concatenate them together:

string output = "What Operation you need to perform\r\n"  
    "A-Addition:\r\n"  
    "S-Subtraction:\r\n"  
    "...";
Console.WriteLine(output);
  •  Tags:  
  • c#
  • Related