Home >Backend Development >C++ >How Do I Read an Integer from User Input in C#?
Reading Integer Input in C#
C#'s Console.ReadLine()
method inherently reads console input as a string. To obtain an integer value, you must explicitly convert the input.
The Convert.ToInt32()
Approach
The simplest method is using Convert.ToInt32()
. This function directly converts a string to an integer.
Here's an example:
<code class="language-csharp">Console.WriteLine("1. Add account."); Console.WriteLine("Enter your choice: "); int userChoice = Convert.ToInt32(Console.ReadLine());</code>
This code snippet first prompts the user for input. Console.ReadLine()
captures the input as a string. Convert.ToInt32()
then transforms this string into an integer, storing the result in the userChoice
variable. Note that this method will throw an exception if the user enters non-numeric input. Error handling (e.g., using a try-catch
block) is recommended for robust applications.
The above is the detailed content of How Do I Read an Integer from User Input in C#?. For more information, please follow other related articles on the PHP Chinese website!