C# - Reading Number Input (and other console commands)
Posted: Fri Mar 27, 2009 2:46 pm
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;
Here are some basic console commands;
And now for the part I struggled with;
Have fun
- Ryan
EDIT:
You can also use this method for other data types
For example,
Where Jim is a string that contains a float value, and Geoff is a float
- 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
}
}
}
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'
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'
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
}
}
}
EDIT:
You can also use this method for other data types
For example,
Code: Select all
Geoff = float.Parse(Jim);