Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is one approach. It's probably overkill if you're just starting out in C#, since it uses some more advanced aspects of the language. In any case, I hope you find it interesting.</p> <p>It has some nice features:</p> <ul> <li><p>The <code>ReadKeys</code> method takes an arbitrary function for testing whether the string so far is valid. This makes it easy to reuse whenever you want filtered input from the keyboard (e.g. letters or numbers but no punctuation). </p></li> <li><p>It should handle anything you throw at it that can be interpreted as a double, e.g. "-123.4E77".</p></li> </ul> <p>However, unlike John Woo's answer it doesn't handle backspaces.</p> <p>Here is the code:</p> <pre><code>using System; public static class ConsoleExtensions { public static void Main() { string entry = ConsoleExtensions.ReadKeys( s =&gt; { StringToDouble(s) /* might throw */; return true; }); double result = StringToDouble(entry); Console.WriteLine(); Console.WriteLine("Result was {0}", result); } public static double StringToDouble(string s) { try { return double.Parse(s); } catch (FormatException) { // handle trailing E and +/- signs return double.Parse(s + '0'); } // anything else will be thrown as an exception } public static string ReadKeys(Predicate&lt;string&gt; check) { string valid = string.Empty; while (true) { ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) { return valid; } bool isValid = false; char keyChar = key.KeyChar; string candidate = valid + keyChar; try { isValid = check(candidate); } catch (Exception) { // if this raises any sort of exception then the key wasn't valid // one of the rare cases when catching Exception is reasonable // (since we really don't care what type it was) } if (isValid) { Console.Write(keyChar); valid = candidate; } } } } </code></pre> <p>You also could implement an <code>IsStringOrDouble</code> function that returns <code>false</code> instead of throwing an exception, but I leave that as an exercise.</p> <p>Another way this could be extended would be for <code>ReadKeys</code> to take two <code>Predicate&lt;string&gt;</code> parameters: one to determine whether the substring represented the start of a valid entry and one the second to say whether it was complete. In that way we could allow keypresses to contribute, but disallow the <kbd>Enter</kbd> key until entry was complete. This would be useful for things like password entry where you want to ensure a certain strength, or for "yes"/"no" entry.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload