Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read user input from the console?

Tags:

c#

.net

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; Console.WriteLine(b); 
like image 907
MaxCoder88 Avatar asked Sep 02 '11 07:09

MaxCoder88


People also ask

What function can be used to read a user input from the console?

The scanf() and printf() Functions function reads the input from the standard input stream stdin and scans that input according to the format provided. The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided.


1 Answers

I'm not sure what your problem is (since you haven't told us), but I'm guessing at

a = Console.Read(); 

This will only read one character from your Console.

You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:

double a, b; Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz"); if (double.TryParse(Console.ReadLine(), out a)) {   b = a * Math.PI;   Console.WriteLine("Sonuç " + b);  } else {   //user gave an illegal input. Handle it here. } 
like image 103
Øyvind Bråthen Avatar answered Oct 06 '22 08:10

Øyvind Bråthen