Search code examples
c#mathaddition

System.FormatException: Input string was not in a correct format. c#


Sorry if its duplicate. I didn't even know what to write as a title.

Introduction:
I was trying to make the adder as a console application.
Problem:
When I run the program, everything works until the 24th line. It will show an error. (img. 1)
What I tried:
nothing. When I look at the code, I don't see any error there.

Thank you

Code:

void write(string towrite)
{
    Console.WriteLine(towrite);
}

//Lets make calculator
string inputoutput;
int num1;
int num2;
write("CALCULATOR");
write("__________");
write("");
write("Write addition problem:");
scitani:
inputoutput = Console.ReadLine();
num1 = Convert.ToInt32(inputoutput.Substring(0, inputoutput.IndexOf('+')));
num2 = Convert.ToInt32(inputoutput.Substring(num1.ToString().Length + 1, 0));
inputoutput = Convert.ToString(num1 + num2);
Console.Clear();
write("CALCULATOR");
write("__________");
write(inputoutput);
goto scitani;

I'm sorry, but I'm Czech and I have VS in Czech. As you can see in img. 1.

img. 1


Solution

  • You want to use Substring without a second parameter, then you take the remaining part until end, otherwise you take the part with the specified length.

    You should also use int.TryParse if you handle user input. Here is a sample:

    void Main()
    {
        int? result = CalcPlus("10 + 17");
        Console.WriteLine(result);
    }
    
    static int? CalcPlus(string input)
    {
        int plusIndex = input.IndexOf('+');
        if(plusIndex == -1)
        {
            return null;
        }
        
        string first = input.Remove(plusIndex).Trim(); // same as Substring(0, plusIndex).Trim()
        string last = input.Substring(plusIndex + 1).Trim();
        
        if(!int.TryParse(first, out int firstInt))
        {
            return null;
        }
        
        if(!int.TryParse(last, out int lastInt))
        {
            return null;
        }
        
        return firstInt + lastInt;
    }