1

I am trying to save the value i get through Console.Read() in an Integer, but whatever i type in my keyboard, the console always gives out 13. I tried to copy an example code, which definitly has to work, but im still only getting 13 as value.

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Read();
            int Test = Console.Read();
            Console.WriteLine(Test);
        }
    }
} 

After i typed in a number, it always shows '13' in the console.

  • 2
    13 - is a key code of _enter_. You want to use [Console.ReadLine](https://learn.microsoft.com/en-us/dotnet/api/system.console.readline?view=netframework-4.8) – vasily.sib Jan 30 '20 at 08:18

3 Answers3

2

Console.Read() reads first character from input stream.

In your case, You are trying to convert second character of input stream(i.e.after first Console.Read()) which is Carriage return and its ASCII value is 13, Test variable which is of type int, storing carriage return in integer format. i.e 13

If you want to convert first character from input stream, then try below

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            int Test = Console.Read();  //Or you can use Console.ReadLine() to read entire line.
            Console.WriteLine(Test);//Print first character of input stream
        }
    }
} 
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
1

Here, you have to use Console.ReadLine to read the number. As Console.ReadLine returns string, you have to convert it to Int32. The following code will fix the issue

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
             int Test = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(Test);
        }
    }
} 
Melvin
  • 195
  • 1
  • 7
0

Try changing this to:

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            int Test = Console.ReadLine();
            Console.WriteLine(Test);
        }
    }
} 

Since 13 is key code for enter, you are probably getting that number from trying to read the whole line.

Demolition Chico
  • 73
  • 1
  • 2
  • 6