How to read characters from keyboard before getting period and count the number of spaces

I am very new to C # and OOP and stackoverflow. This is my first scenario (a few questions)

I want the user to enter characters until a period (.) Is received, and counting and reporting the number of spaces.

Can I achieve this? (Not sure if you always hit to hit Enter / Return to submit)

Can I do this without using strings? (I haven't looked at the lines yet, this is a self learning exercise and I believe the solution should be very simple, but I'm getting unusual results.)

I tried the following, but the program exits before I see results, although I added at the end Console.Read();

, which usually works ...

class CountSpaces
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter characters,finish with a period (\".\"");
            char ch;
            int spaces=0;
            do
            {
                ch = (char)Console.Read();                
                if (ch == ' ')
                {                 
                    spaces++;
                }
            } while (ch != '.');

            Console.WriteLine("Number of spaces counted = {0}",spaces);
            Console.Read();
        }
    }

      

+3


source to share


6 answers


Use Console.ReadKey()

instead Console.Read()

.

  • Console.ReadKey()

    returns if a key is pressed between you after the call Console.ReadKey()

    .
  • Console.Read()

    reads a character as in a stream (not useful at all in your case).


To get char

obtained ReadKey

, use:ch = Console.ReadKey().KeyChar;

+4


source


You want ReadKey

, not Read

. The latter just reads the next character if it exists on the stream and returns -1 if not, as it won't wait (and you probably aren't typing that fast!)



0


source


Use Console.ReadKey () to get ConsoleKeyInfo . Then he checks the pressing Key . You don't need to work with symbols:

int spaces = 0;
ConsoleKey key;
do
{
    key = Console.ReadKey().Key;
    if (key == ConsoleKey.Spacebar)
        spaces++;
}
while (key != ConsoleKey.OemPeriod);

Console.WriteLine("Number of spaces counted = {0}",spaces);

      

Keep in mind that the period key on the NumPad matters ConsoleKey.Decimal

. So, if you need to handle both period keys, you should write the following condition:

while (key != ConsoleKey.OemPeriod && key != ConsoleKey.Decimal);

      

0


source


If you want to see the result, you simply use ReadKey:

class CountSpaces
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter characters,finish with a period (\".\"");
        char ch;
        int spaces = 0;
        do
        {
            ch = (char)Console.Read();
            if (ch == ' ')
            {
                spaces++;
            }
        } while (ch != '.');

        Console.WriteLine("Number of spaces counted = {0}", spaces);
        Console.ReadKey();
    }
}

      

However, I think the program becomes more interesting if you update it to the following:

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("Enter characters,finish with a period (\".\"");
            char ch;
            int spaces = 0;
            do
            {
                ch = (char)Console.Read();
                if (ch == ' ')
                {
                    spaces++;
                }
            } while (ch != '.');

            Console.WriteLine("Number of spaces counted = {0}", spaces);
        }
    }
}

      

0


source


In my example it is used Console.ReadKey

instead of Console.Read

:

class Program
{
    static void Main(string[] args)
    {
        int spaces = 0;
        char key;
        while ((key = Console.ReadKey().KeyChar) != '.') {
            if (key == ' ')
                spaces++;
        }
        Console.WriteLine();
        Console.WriteLine("Number of spaces: {0}", spaces);
        Console.ReadKey();
    }
}

      

0


source


If we create a helper method that creates a sequence of keys from the console:

public static IEnumerable<char> ReadKeys()
{
    while (true)
    {
        yield return Console.ReadKey().KeyChar;
    }
}

      

This allows us to write a query describing exactly what you want:

var spaces = ReadKeys()
    .TakeWhile(c => c != '.')
    .Count(c => c == ' ');

      

Take characters until you get a period and count the number of spaces.

0


source







All Articles