Search code examples
c#parsingloopsconsole

read user input of double type


I have found this answered in other places using loops, but I wasn't sure if there is actually a function that I'm not finding that makes this easier, or if this is a possible (in my opinion) negative side to C#.

I'm trying to read in a double from user input like this:

Console.WriteLine("Please input your total salary: ") // i input 100
double totalSalary = Console.Read(); //reads in the 1, changes to 49.

I've found a couple other posts on this, and they all have different answers, and the questions asked aren't exactly the same either. If i just want the user input read in, what is the best way to do that?


Solution

  • You'll have to check the entire thing on it's way in.. as Console.Read() returns an integer.

    double totalSalary;
    if (!double.TryParse(Console.ReadLine(), out totalSalary)) {
        // .. error with input
    }
    // .. totalSalary is okay here.