Home >Backend Development >C++ >How Do I Read an Integer from User Input in C#?

How Do I Read an Integer from User Input in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-24 05:11:12435browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn