Page 1 of 1

C# - Reading Number Input (and other console commands)

Posted: Fri Mar 27, 2009 2:46 pm
by RyanPridgeon
Well I'm just starting learning C# properly, and I found some trouble finding out some things. So I decided to attempt to help people by posting this here.

- Also to the moderators; I think it would be better if you called this a tutorial forum, because in the end, most snippets end up teaching so much anyway!

So basically in C# you have your "using" (or includes/imports), then your namespace, then your program class, then your main function;

Code: Select all

using System;

namespace learncsharp
{
    class Program
    {
        static void Main(string[] args)
        {
           // program runs here
        }
    }
}
Here are some basic console commands;

Code: Select all

Console.Write("Hello, World!"); // writes hello world to the console

Console.WriteLine("Hello, World!"); // writes hello world to the console, and starts a new line

Console.Clear(); // clears the console screen

Code: Select all

string Thing;
Thing = Console.ReadLine(); // reads a line of keyboard input and stores it inside 'Thing'

And now for the part I struggled with;

Code: Select all

int Number; 
string Thing;
Thing = Console.ReadLine();
Number = int.Parse(Thing); // reads user input, then converts to a integer and stores inside 'Number'
Have fun

Code: Select all

// This is a program to help those who have trouble working out how to read
// numbers from the console (like I did)
// The Parse function looks very useful. Thankyou to functionx.com!

using System;
using System.Collections.Generic;
using System.Text;

namespace learncsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int Input; // a variable to hold the number
            string strNumber; // a variable to hold the user input

            strNumber = Console.ReadLine(); // take input from the keyboard
            Input = int.Parse(strNumber); // convert the input into a number

            Input += 5; // add five to the number
            Console.Write(Input); // write the number to the screen

            Console.ReadLine(); // wait for input to exit
        }
    }
}


- Ryan

EDIT:

You can also use this method for other data types

For example,

Code: Select all

Geoff = float.Parse(Jim);
Where Jim is a string that contains a float value, and Geoff is a float

Re: C# - Reading Number Input (and other console commands)

Posted: Sun Apr 05, 2009 2:55 pm
by Keevu
Sweetness Im a newb to programming console, I prefer to program in windows form. But console is definetly useful thanks a ton.

C# for life! 8-)