How to read input as integer in C#?

WBOY
Release: 2023-09-01 16:21:10
forward
1170 people have browsed it

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

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

res = Convert.ToInt32(val);
Copy after login

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();
Copy after login

After reading, convert it to an integer.

int res;
res = Convert.ToInt32(val);
Copy after login

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);
   }
}
Copy after login

Output

Input from user:
Input = 0
Copy after login

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

Input from user: 2
Input = 2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!