Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add two numbers using Console.ReadLine()

I want to add two numbers using Console.ReadLine(), but it gives me the error

Invalid expression term 'int'

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Enter a number:");
      string number1 = Console.ReadLine();
      Console.WriteLine("Enter another number:");
      string number2 = Console.ReadLine();
      Console.WriteLine("The sum of those numbers is:");
      Console.WriteLine(int(number1) + int(number2));
    }
  }
}

Could you help?

>Solution :

Use the Convert.ToInt32() method to convert from string to int.

Console.WriteLine(Convert.ToInt32(number1) + Convert.ToInt32(number2));

See How can I convert String to Int? for more examples or alternatives.


Note: You write

string s = "42";
int i = int(s); // Compiler error Invalid Expression term

This syntax is used for type casting in languages like Pascal or Python. But in C based languages like C#, C++ or Java you use a different syntax:

string s = "42";
int i = (int)s; // Compiler error invalid cast

Round brackets around the type name, not around the value. This will still not work, though, because there is no direct cast from type string to type int in C#. It would work for different types:

double d = 42d;
int i = (int)d; // Works
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading