Search code examples
c#stringstringbuilder

How i can take multiple int inputs through string builder


How i can take multiple (int) inputs through string builder

my code is

class Solution
{
    public static void Main(string[] args)
    {
        StringBuilder s = new StringBuilder(int.Parse(Console.ReadLine()));
        int a = s[0];
        int b = s[1];
        
        Console.WriteLine(a+b);
    }
}

Solution

  • StringBuilder is for building strings. You want the exact opposite. You want to analyze a string and get its parts.

    Let's assume that the user is entering something like 12 7. Then you can get the parts with

    string input = Console.ReadLine();
    string[] parts = input.Split();
    

    Now the array should have a length of 2. It contains strings. To do math, you must convert strings into numbers.

    int a = Int32.Parse(parts[0]);
    int b = Int32.Parse(parts[1]);
    

    Now you can print

    Console.WriteLine(a + b);
    

    But you could also expect the user to enter one number at a time and call ReadLine() twice.

    Console.Write("Please enter first number: ");
    string s = Console.ReadLine();
    int a = Int32.Parse(s);
    
    Console.Write("Please enter second number: ");
    s = Console.ReadLine();
    int b = Int32.Parse(s);
    
    Console.WriteLine(a + b);
    

    For the sake of simplicity, I have omitted validations.

    In the first example, you would have to check the length of the string array. In both examples you would have to use the Int32.TryParse Method to validate user input. If the input is not like expected you would then have to inform the user about it and ask him to re-enter a correct input.

    This adds a lot of complexity but is essential for a robust application; however, for a simple test code or lesson, this can be omitted.