[c#] How can I read user input from the console?

I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.

double a,b;
a = Console.Read();
b = a * Math.PI;

This question is related to c# .net console

The answer is

        double a,b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
            a = Convert.ToDouble(Console.ReadLine());
            b = a * Math.PI;
            Console.WriteLine("Sonuç " + b); 
        catch (Exception)
            Console.WriteLine("dönüstürme hatasi");

string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
    Console.WriteLine("Wrong input");
double r = d * Math.Pi;

The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.

I think there are some compiler errors.

  • Writeline should be WriteLine (capital 'L')
  • missing semicolon at the end of a line

        double a, b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        a = double.Parse(Console.ReadLine());
        b = a * Math.PI; // Missing colon!
        Console.WriteLine("Sonuç " + b);

Console.Read() takes a character and returns the ascii value of that character.So if you want to take the symbol that was entered by the user instead of its ascii value (ex:if input is 5 then symbol = 5, ascii value is 53), you have to parse it using int.parse() but it raises a compilation error because the return value of Console.Read() is already int type. So you can get the work done by using Console.ReadLine() instead of Console.Read() as follows.

int userInput = int.parse(Console.ReadLine());

here, the output of the Console.ReadLine() would be a string containing a number such as "53".By passing it to the int.Parse() we can convert it to int type.

Sometime in the future .NET4.6

//for Double
double inputValues = double.Parse(Console.ReadLine());

//for Int
int inputValues = int.Parse(Console.ReadLine());

string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console

Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.

Console.ReadLine() reads a string (so then you need to change the string to a double)

a = double.Parse(Console.ReadLine());

Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.


To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.

If you'd like to perform some sort of error checking, simply do this:

if ( double.TryParse(Console.ReadLine(), out a) ) {
  Console.Writeline("Sonuç "+ a * Math.PI;); 
else {
  Console.WriteLine("Invalid number entered. Please enter number in format: #.#");

Thanks to Öyvind and abatischev for helping me refine my answer.

You're missing a semicolon: double b = a * Math.PI;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version= How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working