Complex I / O using Console.WriteLine ()

I am currently teaching myself C # after years of working in C ++ only. Needless to say, there was a lot that I needed to retrain. My question here is the following:

What's the best approach in a Windows Console application to print (write to the console window) complex information containing multiple variables, lines of text, and newlines?

Simply put, how would I translate something similar to the following C ++ code to C #:

int x = 1; int y = 2; double a = 5.4;

cout << "I have " << x << " item(s), and need you to give" << endl
     << "me " << y << " item(s). This will cost you " << a << endl
     << "units." << endl;

      

In C ++, this will output the following to the console:

I have 1 item (s) and you need to give

give me 2 item (s). It will cost you 5.4

units.

This example is completely arbitrary, but I often have short but complex messages like this in my programs. Do I have to completely retrain how I format the output, or are there similar features in C # that I haven't found yet (I've digged through a lot of Console.IO documentation).

+3


source to share


1 answer


You can supply the seat holders on the line you write to the console, and then provide values ​​to replace those seat holders, for example:

Console.WriteLine("I have {0} item(s), and need you to give\r\n" +
                  "me {1} item(s). This will cost you {2} \r\nunits.", x, y, a);

      

I think for readability, I would split it:



Console.WriteLine("I have {0} item(s), and need you to give", x);
Console.WriteLine("me {0} item(s). This will cost you {1} ", y, a);
Console.WriteLine("units.");

      

As BradleyDotNet pointed out, the method Console.WriteLine()

does not directly perform magic. It calls String.Format

, which in turn uses StringBuilder.AppendFormat

.

If you want to see what's going on inside you can check the source code here .

+8


source







All Articles