Home >Backend Development >C++ >How to Read Integer Input from the Command Line in C#?
Efficiently Handling Integer Input from the C# Command Line
In C#, acquiring integer input directly from the command line requires a straightforward approach. While Console.ReadLine()
returns a string, direct integer conversion is possible using Convert.ToInt32()
.
This function transforms a string input into its integer equivalent. Here's a practical example:
<code class="language-csharp">int userInput = Convert.ToInt32(Console.ReadLine());</code>
Consider this scenario:
<code class="language-csharp">Console.WriteLine("1. Add account."); Console.WriteLine("Enter your choice: "); Console.ReadLine(); // Currently accepts string input</code>
To correctly handle integer input, modify the last line:
<code class="language-csharp">int choice = Convert.ToInt32(Console.ReadLine());</code>
This revised code captures user input, converts it to an integer, and assigns it to the choice
variable for subsequent use within your program. This ensures that your application correctly processes numerical user choices.
The above is the detailed content of How to Read Integer Input from the Command Line in C#?. For more information, please follow other related articles on the PHP Chinese website!