Oto Shavadze
Oto Shavadze

Reputation: 42803

Displaying typed characters on new line

May be funny question, I am very newbie in C#

class Program
{
   static void Main(string[] args)
   {
       int a;
       a = Convert.ToInt32(Console.ReadLine());
       Console.WriteLine(a);
       Console.ReadKey();
   }
}

I expected that after typing any character, these character would be written on new line in console, though these are printed on one line. where I am wrong?

P.S.

Console.WriteLine("ASD");
Console.WriteLine("DSA");

this displayed as expected:

ASD
DSA

Upvotes: 1

Views: 86

Answers (2)

Shane
Shane

Reputation: 336

Every call of the Console.WriteLine() method prints a new line. What your example does is take all the input and print that input a single time.

You could try this instead:

class Program
{
    static void Main(string[] args)
    {
        int a;

        while(true)
        {
            a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(a);
        }
    }
}

Edit: included version that uses char and Console.Read() as that seems to be more appropriate

class Program
{
    static void Main(string[] args)
    {
        char a;

        while(true)
        {
            a = (char)Console.Read();
            Console.WriteLine(a);
        }
    }
}

Upvotes: 3

Fabjan
Fabjan

Reputation: 13676

Console.ReadLine() method does not terminate the line (as you would probably expect). A quote From MSDN :

A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. The returned string does not contain the terminating character(s).

So you just take the line that is not terminated and print it out.

Source : https://msdn.microsoft.com/en-us/library/system.console.readline(v=vs.110).aspx

Upvotes: 1

Related Questions