2

In Java, if we want to read an user input from the console, we can do the following.

Scanner scn = new Scanner (System.in);
int x;

x = scn.nextInt();  //Receive integer input

In C#, I am assuming we do this:

int x;

x = Console.Read();  //Receive integer input

But when I enter 7 , the output is 55.

The other 2 options for reading inputs are ReadLine() which is probably used for reading strings, and ReadKey() which is proabably for detecting which key you pressed (Please correct me if I am wrong).

Please don't tell me that we have to use ReadLine and parse the entire value to int everytime, that will be awful :-(

EDIT: In SO, a similar question was raised (c# Console.Read() and Console.ReadLine() problems), but all the solutions given was to use int.TryParse and series of codes just to receive a int or double input, which I find it too inconvenient just to do a simple task.

I found out that we could actually do this:

int a = int.Parse(Console.ReadLine());

So instead of asking a duplicated question, my new question is: Is it equivalent to Java's scn.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?

Community
  • 1
  • 1
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • 1
    `Read` returns only a single char, `55` is ASCII for `'7'`. Use `ReadLine` together with `int.Parse` or `int.TryParse` – CodesInChaos May 25 '14 at 15:37
  • 1
    _"Please don't tell me that we have to use ReadLine and parse the entire value to int everytime"_ - yeah you do. See [c# Console.Read() and Console.ReadLine() problems](http://stackoverflow.com/questions/12308098/c-sharp-console-read-and-console-readline-problems). – CodeCaster May 25 '14 at 15:38
  • This is basically what Java's `Scanner.nextInt` does, only it uses regex to match the pattern, and it hides it in a single call. You can do the same here, hiding a call to `int.TryParse(Console.Read)` in a helper method or extension method. – Avner Shahar-Kashtan May 25 '14 at 15:43
  • @CodeCaster 55 is UTF-16 for '7'; ASCII is irrelevant. No matter what Console.InputEncoding is (and it's almost certainly not ASCII), the result is the first UTF-16 code-unit. – Tom Blodget May 26 '14 at 02:28
  • 1
    I guess you mean @CodesInChaos, not me. :) Though [any ASCII character maps to the same Unicode character](http://stackoverflow.com/questions/10361579/are-unicode-and-ascii-characters-the-same). – CodeCaster May 26 '14 at 07:52
  • @CodeCaster Question edited. See if you can remove the duplicate mark. – user3437460 May 26 '14 at 12:26
  • It is just as safe as Java's. It will throw an exception if the input isn't an integer. If you want a more elaborate answer, I can vote to reopen, but please clarify what you mean with "safe". – CodeCaster May 26 '14 at 12:28
  • Why the down vote ..? Mind dropping a reason, so we can improve next time? – user3437460 May 26 '14 at 14:03
  • Related post [here](https://stackoverflow.com/q/722270/465053) : C# doesn't have any equivalent of Java's `Scanner` class which can read whitespace-delimited tokens. – RBT Aug 29 '17 at 01:54

4 Answers4

2

Is it equivalent to Java's scanner.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?

Yes. Java's Scanner.nextInt() throws an exception when no integer input has been received, as does .NET's int.Parse(Console.ReadLine()).

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    Aren't they actually different if there are _two_ integers on one line, separated by space? Will not two successive `Scanner.nextInt()` return two integers from one line, while `int.Parse(Console.ReadLine())` will return the first only (or none at all?)? – Petr Nov 29 '15 at 11:44
  • 3
    @Petr you're absolutely right, according to the [documentation](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) the scanner also supports whitespace. So if the user enters `1[space]2[enter]`, you can call `nextInt()` twice; once to get the `1`, the second time to get the `2`. – CodeCaster Nov 29 '15 at 12:00
2

This may be a year late, but...

    static int GetInt() {
        int integer = 0;
        int n = Console.Read();
        while (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
            n = Console.Read();
        while (n >= '0' && n <= '9') {
            integer = integer * 10 + n - '0';
            n = Console.Read();
        }
        return integer;
    }

This is more or less the same as Java's nextInt() method. It doesn't support negative values as it currently is, but it can be easily implemented by checking if the first read value is '-' and if it is, multiply the final value by -1.

0

Yes, you need to use ReadLine, parsing the input is not so hard.Just use TryParse method:

int input;
bool isValid = int.TryParse(Console.ReadLine(),out input);

if(isValid)
{
   ...
}

Console.Read reads the next character from console, and it returns the ASCII code of the char, that's why you are getting 55 instead of 7.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • 1
    Is this the simplest way to receive an `int` input? Because receiving inputs from Java, C and C++ are very straight forward. I am surprised C# makes it so inconvenient. – user3437460 May 25 '14 at 15:52
0

You can use this library from NuGet which provides Java Scanner/C++ cin style input in C#: https://www.nuget.org/packages/Nakov.IO.Cin/

Sample:

using System;
using Nakov.IO;
 
public class EnterNumbers
{
    static void Main()
    {
        int n = Cin.NextInt();
 
        int[] numbers = new int[n];
        for (int i = 0; i < n; i++)
            numbers[i] = Cin.NextInt();
 
        for (int i = 0; i < n; i++)
            Console.Write(numbers[i] + " ");
    }
}
Felix An
  • 309
  • 4
  • 13