Search code examples
c#mathconsole-applicationstring-formattingtext-formatting

Aligning strings in the terminal with c#


I am looking for a little assistance. I am new to C# and am trying to build a simple addition/ subtraction game for my kid to practice his skills. I have the basics working (more to develop on it) so far but there is one issue that I am looking to fix.

How I have the string in the code set up, it will print a couple of random numbers on separate lines. I am wanting to align these numbers to the right, but there will not always be a set number of digits. Here is the code (probably sloppy, so I apologize) thus far.

/* Basic build
- There are two numbers up to 6 numbers
- Number 1 must be higher than number 2 (-'s are still out of scope)
- Operation is randomized
- 10 Questions per round
- There will need to be a scoring system
*/

int num1;
int num2;
int answer;
string opperation = "+";
string guess;
int finalAnswer;
Random randNumber = new Random();
int score = 0;



for (int i = 0; i < 10; i++)
{
    num1 = randNumber.Next(0, 101);
    num2 = randNumber.Next(0, 101);
    string num1String = num1.ToString();
    string num2String = num2.ToString();

    answer = num1 + num2;
    Console.WriteLine($"  {num1String}\n+ {num2String}\n---------");
    guess = Console.ReadLine();

    while (!int.TryParse(guess, out finalAnswer))
    {
        Console.WriteLine("That is not a valid number. Please guess again:");
        guess = Console.ReadLine();
    }
    if (finalAnswer == answer)
    {
        score++;
        Console.WriteLine("That is correct! :)\n\n");
    }
    else
    {
        Console.WriteLine("That is Incorrect. :(\n\n");
    }
}

Console.WriteLine($"Your score is {score} out of 10");

An example of the the current output could be

  100
+ 5
_________

I am looking to make it more like

      100
+       5
_________

I have been researching but am unable to find a solution to this.


Solution

  • The string class has a built in PadLeft method you could use.

    For example:

    Console.WriteLine($"{num1String.PadLeft(10)}\n{operation}{num2String.PadLeft(10 - operation.Length)}\n---------");
    

    I used your operation variable that you defined, and I took it's length into consideration when determining the padding for num2String.