Read a string from standard input in C#
This post will discuss how to read a string from standard input in C#.
The Console class represents the standard input, output, and error streams for console applications. It is used for reading data to the standard input and writing data from the standard output stream. We can Console.In
to access the standard input stream.
The recommended method to read a string from standard input is using the built-in method ReadLine(). It reads and returns the next line of characters from the standard input stream, or null when no more lines are available. The following example reads a line from the standard input stream and stores it in a string.
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { string s = Console.In.ReadLine(); Console.WriteLine(s); } } |
The above example illustrates the use of the In
property to read from stdin. It returns a TextReader
that represents the standard input stream. You can also directly invoke the ReadLine()
method from the Console
class, as shown below.
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { string s = Console.ReadLine(); Console.WriteLine(s); } } |
That’s all about reading a string from standard input in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)