Home >Backend Development >C#.Net Tutorial >How to read input as integer in C#?

How to read input as integer in C#?

WBOY
WBOYforward
2023-09-01 16:21:101288browse

如何在 C# 中将输入读取为整数?

To read input as an integer in C#, use the Convert.ToInt32() method.

res = Convert.ToInt32(val);

Let's see how -

Convert.ToInt32 Converts the specified string representation of a number to an equivalent 32-bit signed integer.

First, read the console input -

string val;
val = Console.ReadLine();

After reading, convert it to an integer.

int res;
res = Convert.ToInt32(val);

Let’s see an example -

Example

Live Demonstration

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string val;
      int res;
   
      Console.WriteLine("Input from user: ");
      val = Console.ReadLine();

      // convert to integer
      res = Convert.ToInt32(val);

      // display the line
      Console.WriteLine("Input = {0}", res);
   }
}

Output

Input from user:
Input = 0

The following is the output. Input is entered by the user.

Input from user: 2
Input = 2

The above is the detailed content of How to read input as integer in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete