1

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.

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked swimmingly, Thanks @Frosch
1

Doing e.g.

Console.WriteLine("  {0,8}\n+ {1,8}\n----------", num1, num2);

should help.

3 Comments

Typical int, as a string, is 1 to 11 characters long. 8 may be insufficient.
The result of randNumber.Next(0, 101); won't be 11 characters, I think. But anyway, just wanted to show some example based on the sample code in the question, using a possible formatting option.
Fair point.....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.