Nakov.com

Thoughts on Software Engineering

  • About
  • Books
  • Courses
  • Videos
  • Presentations
  • Research
  • Publications
  • Others
  • Contacts
  • RSS Feed
  • Home

Categories

  • .net (81)
  • blog (330)
  • bulgarian (203)
  • career (21)
  • contests (28)
  • courses (64)
  • english (131)
  • HTML5 (6)
  • java (44)
  • seminars (81)
  • НЛП (7)
  • предприемачество (3)

Networked Blogs

Follow this blog

Recent Posts

  • Представяне на NASA Space Apps Challenge на 2 април 2013
  • Как да презентираме вдъхновяващо с майсторлък? Мурафетите на Наков
  • Пролетен прием в софтуерната академия: 500 нови студента от април
  • Безплатен курс “Бизнес умения за софтуерни инженери” – от 27 март
  • 580 продължават безплатното си обучение в софтуерната академия след изпитите по CSS и C# част 2

Partners

Intro C# Programming Book by Svetlin Nakov
Telerik Academy

My Projects

  • GWT Advanced Table
  • Internet Programming with Java Book
  • Intro C# Programming Book
  • Intro Java Programming Book
  • Java For Digitally Signing Documents In Web Book
  • Programming for .NET Framework Book
  • Software University

Useful Links

  • Bulgarian Association of Software Developers (BASD)
  • Free Java and Java EE Course
  • NLP Club Bulgaria
  • Stefan Kanev's Blog
  • Telerik Academy
  • Telerik Kids Academy
  • Telerik School Academy

Tags

AJAX ASP.NET C# CSS development HTML Java JavaScript NET Programming Software SQL telerik Академия на Телерик Академия на Телерик за ученици академия академия за софтуерни инженери безплатен курс безплатни курсове безплатни уроци безплатно безплатно обучение курс обучение програмиране разработка на софтуер семинар софтуерна академия състезание телерик

Most Viewed Posts

  • Rejected a Program Manager Position at Microsoft Dublin – My Successful Interview at Microsoft
  • Svetlin Nakov – About Me
  • Innovations in Software Тest Automation – конференция за QA инженери – 25.11.2011
  • Online AES Encryption Tool
  • Disable Certificate Validation in Java SSL Connections
  • My Interview at Google in Zurich
  • Native SQL Queries in Entity Framework
  • JAX-RS, @Path, @PathParam and Optional Parameters
  • Svetlin Nakov – Books
  • NHibernate Lazy Loading BLOB column

Author: Svetlin Nakov

November 23, 2011

  • Svejo.net
  • Tweet

Simplified Console Input Class for C#, Similar to “cin >> a >> b” in C++ and java.util.Scanner

Recently I was again asked how do we perform “cin >> a >> b” in C# or how we can enter a sequence of numbers from the console in C#. In C++ we have very powerful class called “cin” (more correctly std::cin located in the standard library “iosteam”) that overloads the >> operator and allows entering anything from the standard input (stdin): numbers, characters, strings and other data types.

I searched for “cin in C#” and found nothing similar to “std::cin” for C#, so I needed to write such a class.

The Nakov.IO.Cin Class – “cin” Functionality for C# / .NET

Initially I had an idea to implement my C# “cin” class exactly like in C++. Unfortunately this was impossible because the C# language has certain limitations:

  • You cannot override the >> operator in C# for any type except int
  • You cannot override the >> operator in C# for output / by-ref types (e.g. out int, ref int)
  • You cannot add extension methods to the Console class because it is static (so additions like Console.Cin, Console.NextInt(), Console.In << x << b and Console.Cin.NextInt() cannot be added to it)

Finally I decided to implement my C# console simplifies reader it in a way similar to the Java syntax used in the java.util.Scanner class. See the code below:

namespace Nakov.IO
{
    using System;
    using System.Text;
    using System.Globalization;

    /// <summary>
    /// Console input helper for C# and .NET. Allows simplified reading of numbers and string
    /// tokens from the console in a way similar to "cin" in C++ and java.util.Scanner in Java.
    /// </summary>
    ///
    /// <copyright>
    /// (c) Svetlin Nakov, 2011 - http://www.nakov.com
    /// </copyright>
    ///
    /// <example>
    /// // In C++ we will use "cin >> x >> y;"
    /// // Using Nakov.IO.Cin we can do the same as follows:
    /// int x = Cin.NextInt();
    /// double y = Cin.NextDouble();
    /// </example>
    ///
    public static class Cin
    {
        /// <summary>
        /// Reads a string token from the console
        /// skipping any leading and trailing whitespace.
        /// </summary>
        public static string NextToken()
        {
            StringBuilder tokenChars = new StringBuilder();
            bool tokenFinished = false;
            bool skipWhiteSpaceMode = true;
            while (!tokenFinished)
            {
                int nextChar = Console.Read();
                if (nextChar == -1)
                {
                    // End of stream reached
                    tokenFinished = true;
                }
                else
                {
                    char ch = (char)nextChar;
                    if (char.IsWhiteSpace(ch))
                    {
                        // Whitespace reached (' ', '\r', '\n', '\t') -->
                        // skip it if it is a leading whitespace
                        // or stop reading anymore if it is trailing
                        if (!skipWhiteSpaceMode)
                        {
                            tokenFinished = true;
                            if (ch == '\r' && (Environment.NewLine == "\r\n"))
                            {
                                // Reached '\r' in Windows --> skip the next '\n'
                                Console.Read();
                            }
                        }
                    }
                    else
                    {
                        // Character reached --> append it to the output
                        skipWhiteSpaceMode = false;
                        tokenChars.Append(ch);
                    }
                }
            }

            string token = tokenChars.ToString();
            return token;
        }

        /// <summary>
        /// Reads an integer number from the console
        /// skipping any leading and trailing whitespace.
        /// </summary>
        public static int NextInt()
        {
            string token = Cin.NextToken();
            return int.Parse(token);
        }

        /// <summary>
        /// Reads a floating-point number from the console
        /// skipping any leading and trailing whitespace.
        /// </summary>
        /// <param name="acceptAnyDecimalSeparator">
        /// Specifies whether to accept any decimal separator
        /// ("." and ",") or the system's default separator only.
        /// </param>
        public static double NextDouble(bool acceptAnyDecimalSeparator = true)
        {
            string token = Cin.NextToken();
            if (acceptAnyDecimalSeparator)
            {
                token = token.Replace(',', '.');
                double result = double.Parse(token, CultureInfo.InvariantCulture);
                return result;
            }
            else
            {
                double result = double.Parse(token);
                return result;
            }
        }

        /// <summary>
        /// Reads a decimal number from the console
        /// skipping any leading and trailing whitespace.
        /// </summary>
        /// <param name="acceptAnyDecimalSeparator">
        /// Specifies whether to accept any decimal separator
        /// ("." and ",") or the system's default separator only.
        /// </param>
        public static decimal NextDecimal(bool acceptAnyDecimalSeparator = true)
        {
            string token = Cin.NextToken();
            if (acceptAnyDecimalSeparator)
            {
                token = token.Replace(',', '.');
                decimal result = decimal.Parse(token, CultureInfo.InvariantCulture);
                return result;
            }
            else
            {
                decimal result = decimal.Parse(token);
                return result;
            }
        }
    }
}

How Cin.NextDouble() Works?

My class Nakov.IO.Cin allows simplified entering string tokens, integer numbers, floating-point numbers and decimal numbers in C# from the standard input (the console). When reading a sequence of numbers, we can separate them with a single space, multiple spaces, new line separators or any other sequence of whitespace characters: spaces, tabs, new lines (\n, \r\n), etc.

In addition Nakov.IO.Cin solves the culture-specific problem with the decimal point separator which may be “,” in some countries (like Bulgaria) and “.” in other countries (like USA and Canada). The Cin.NextDouble() and Cin.NextDecimal() methods accept a Boolean parameter which specifies whether the numbers should be parsed using the default decimal separator (specified in the regional settings in Windows) or by accepting both separators: “.” and “,”. By default both decimal separators are accepted when entering numbers by Nakov.IO.Cin.NextDouble() and Nakov.IO.Cin.NextDecimal().

Using the Nakov.IO.Cin Class – Example

In the below example I show how to use the class “Nakov.IO.Cin” to enter integer numbers, floating-point numbers, decimal numbers and string tokens:

using System;
using Nakov.IO; // see http://www.nakov.com/tags/cin

public class CinExample
{
    static void Main()
    {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();

        Console.Write("Enter two integers x and y separated by whitespace: ");
        // cin >> x >> y;
        int x = Cin.NextInt();
        double y = Cin.NextDouble();

        Console.Write("Enter your age: ");
        int age = int.Parse(Console.ReadLine());

        Console.WriteLine("Name: {0}, Age: {1}", name, age);
        Console.WriteLine("x={0}, y={1}", x, y);

        Console.Write("Enter a positive integer number N: ");
        int n = Cin.NextInt();

        Console.Write("Enter N decimal numbers separated by a space: ");
        decimal[] numbers = new decimal[n];
        for (int i = 0; i < n; i++)
        {
            numbers[i] = Cin.NextDecimal();
        }

        Console.Write("The numbers in ascending order: ");
        Array.Sort(numbers);
        for (int i = 0; i < n; i++)
        {
            Console.Write(numbers[i]);
            Console.Write(' ');
        }
        Console.WriteLine();

        Console.WriteLine("Enter two strings seperated by a space: ");
        string firstStr = Cin.NextToken();
        string secondStr = Cin.NextToken();
        Console.WriteLine("First str={0}", firstStr);
        Console.WriteLine("Second str={0}", secondStr);
    }
}

Translating from C++ “cin” to C# Using the C# “cin” Class

Once you have included the class Nakov.IO.Cin to your C# / VB.NET project, you could translate the following C++ program into C#:

Sample C++ code entering a number N and a sequence of N integer numbers, separated by a space (or any other sequence of whitespace characters):

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;

    int* numbers = new int[n];
    for (int i = 0; i < n; i++)
    {
        cin >> numbers[i];
    }

    for (int i = 0; i < n; i++)
    {
        cout << numbers[i] << ' ';
    }
}

The same code written in C# using the C# “cin” class (Nakov.IO.Cin) is as follows:

using System;
using Nakov.IO; // see http://www.nakov.com/tags/cin

public class EnteringNumbers
{
    static void Main()
    {
        int n;
        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] + " ");
        }
    }
}

With both the programs (the C++ and the C# one) you are free to enter all the requested numbers on a single line (e.g. “3   1 –2   3”) or on separate lines (e.g. “\r\n 3 \r\n   1 \t –2 \r\n\r\n  3”)) and they will be parsed correctly, as expected.

Download the Nakov.IO.Cin Class

  • Download the full source code and examples: Nakov.IO.Cin.zip.
  • Download the C# class source code only: Cin.cs.
  • Browse the Nakov.IO.Cin project repository at GitHub.

Tags: C#, C# cin, C# cin class, C# console, C# console cin, C++ cin for C#, cin, cin >> a >> b in C#, cin >> a in C#, cin class C#, cin for .NET, cin for C#, Console.NextDouble(), Console.NextInt(), Console.NextInt() in C#, Console.NextToken(), CSharp, java.util.Scanner, java.util.Scanner in C#, Nakov.IO.Cin, std::cin, std::cin C#, stdin

Previews (12,047), Views (1,295), Comments (5)

5 Comments »

  1. Без дори един юнит тест?

    Comment by Росен — November 24, 2011 @ 18:48

  2. Не съм писал тестове, нямах достатъчно време. Някой ден ще ги напиша…

    Comment by nakov — November 27, 2011 @ 20:11

  3. По-скоро трябваше примерите да са с Generic методи -
    Cin.Next< int >();
    Cin.Next< double >();
    и т.н.

    Comment by Johnny — November 28, 2011 @ 02:51

  4. Между Next-а и () трябваше да има ъглови скоби с type argument (int, double, decimal, etc.) … но блога реши да ги цензурира

    Comment by Johnny — November 28, 2011 @ 02:54

  5. Мдаа, интересно ще се получи с generics.

    Comment by nakov — November 28, 2011 @ 12:59

RSS feed for comments on this post. TrackBack URL

Leave a comment

Top Posts

  • Семинар “Как да си намерим работа в ИТ индустрията?” – CV, cover letter, интервю

  • Университет като за софтуерни инженери: къде да учим програмиране след 12 клас? (класацията на Наков)

  • Rejected a Program Manager Position at Microsoft Dublin – My Successful Interview at Microsoft

  • My Interview at Google in Zurich

Translation

Recent Posts

  • Представяне на NASA Space Apps Challenge на 2 април 2013
  • Как да презентираме вдъхновяващо с майсторлък? Мурафетите на Наков
  • Пролетен прием в софтуерната академия: 500 нови студента от април
  • Безплатен курс “Бизнес умения за софтуерни инженери” – от 27 март
  • 580 продължават безплатното си обучение в софтуерната академия след изпитите по CSS и C# част 2

Recent Comments

  • http://theprostitutiontimes.blogspot.com on Нов безплатен курс по уеб дизайн с HTML 5, CSS и JavaScript – от март в академията на Телерик: Instead, it's diverted hundreds of millions of dollars to two children with autism for" pain...
  • Paul Crocker on X.509 Certificate Validation in Java: Build and Verify Chain and Verify CLR with Bouncy Castle: Thanks - It works fine for me after tidying the code up a bit and...
  • look at this web-site on Безплатните курсове в Академията на Телерик за софтуерни инженери – какво да очакваме за 2011-2012?: But beyond the financial implications it is the most logical thing in the world, but...
  • check This link right Here now on 85 продължават в Софтуерната академия в курса Software Engineering Basics от 17 април: Isn't the very name," National News" mean that it s not just about themedication. Our...
  • Serena-Ilsuospazio.Blogspot.com on Нов безплатен курс по уеб дизайн с HTML 5, CSS и JavaScript – от март в академията на Телерик: The National Governors' Association said Medicaid coverage of farmacia on line was told yesterday he...

Archives

  • March 2013 (4)
  • February 2013 (5)
  • January 2013 (7)
  • December 2012 (1)
  • November 2012 (11)
  • October 2012 (8)
  • September 2012 (8)
  • August 2012 (2)
  • July 2012 (10)
  • June 2012 (1)
  • May 2012 (9)
  • April 2012 (9)
  • March 2012 (9)
  • February 2012 (10)
  • January 2012 (8)
  • December 2011 (5)
  • November 2011 (12)
  • October 2011 (18)
  • September 2011 (16)
  • August 2011 (7)
  • July 2011 (7)
  • June 2011 (2)
  • May 2011 (3)
  • April 2011 (10)
  • March 2011 (8)
  • February 2011 (5)
  • January 2011 (7)
  • December 2010 (3)
  • November 2010 (17)
  • October 2010 (8)
  • September 2010 (4)
  • August 2010 (2)
  • July 2010 (4)
  • June 2010 (3)
  • May 2010 (4)
  • April 2010 (2)
  • March 2010 (1)
  • February 2010 (2)
  • January 2010 (4)
  • December 2009 (3)
  • November 2009 (6)
  • October 2009 (3)
  • September 2009 (6)
  • July 2009 (4)
  • June 2009 (1)
  • May 2009 (3)
  • December 2008 (2)
  • November 2008 (2)
  • September 2008 (1)
  • August 2008 (5)
  • July 2008 (2)
  • June 2008 (4)
  • May 2008 (2)
  • April 2008 (1)
  • March 2008 (2)
  • February 2008 (2)
  • January 2008 (1)
  • December 2007 (4)
  • November 2007 (7)
  • October 2007 (3)
  • September 2007 (9)
  • August 2007 (5)

RSS Academy Forums

  • Answered: Вярно ли е, че допълните съботни упражнения по C# са със задачи подобни на изпита?
  • Краен срок за домашните от Условни конструкции и Цикли
  • Бихте ли попълнили тази анкета?
  • Answered: .NET Ninja Egg
  • Answered: Operators, Expressions and Statements - Задача 12

navigation:

Home About Books Courses Presentations Videos Research Publications Others Contacts
Svetlin Nakov @ Google+

My Projects

  • GWT Advanced Table
  • Internet Programming with Java Book
  • Intro C# Programming Book
  • Intro Java Programming Book
  • Java For Digitally Signing Documents In Web Book
  • Programming for .NET Framework Book
  • Software University

Useful Links

  • Bulgarian Association of Software Developers (BASD)
  • Free Java and Java EE Course
  • NLP Club Bulgaria
  • Stefan Kanev's Blog
  • Telerik Academy
  • Telerik Kids Academy
  • Telerik School Academy

Categories

  • .net
  • blog
  • bulgarian
  • career
  • contests
  • courses
  • english
  • HTML5
  • java
  • seminars
  • НЛП
  • предприемачество

Recent Posts

  • Представяне на NASA Space Apps Challenge на 2 април 2013
  • Как да презентираме вдъхновяващо с майсторлък? Мурафетите на Наков
  • Пролетен прием в софтуерната академия: 500 нови студента от април
  • Безплатен курс “Бизнес умения за софтуерни инженери” – от 27 март
  • 580 продължават безплатното си обучение в софтуерната академия след изпитите по CSS и C# част 2

Copyright © 1999 - 2013 Svetlin Nakov