Marky03

I have been into C++ for a few months and got up to learning functions, pointers, references, and a little OOP. I wanted to experiment with C#, for many personal reasons. It seems to attract me more..

With C++ all you have to do is..

cout << "Enter a num";
cin >> num;

Now, in C#
I don't know how to get a user input for a number.The Console.ReadLine() only does strings I believe. And I remember using something else..but when I entered '4' it output '52', input '5' i get '53'. Thats probably the ASCII codes How can I just get it to output the number An example of a "guess my number" program would be much appreciated Smile

Marky03


Re: Visual C# General C# User Input

Derek Smyth

Hi mate,

You just got to convert the string to a number using the double or int static TryParse method. Here an example of the ReadLine and ReadKey console input.

Code Snippet

static void Main(string[] args)

{

Console.WriteLine("Please enter a number.");

//ReadLine example

string input = Console.ReadLine();

double inputAsNumber;

if (double.TryParse(input, out inputAsNumber) == true)

{

Console.WriteLine("You entered a valid number: {0}", inputAsNumber);

}

else

{

Console.WriteLine("You entered an invalid number");

}

Console.ReadLine();

//ReadKey example

Console.WriteLine("Please enter a number.");

ConsoleKeyInfo key = Console.ReadKey();

if (double.TryParse(key.KeyChar.ToString(), out inputAsNumber) == true)

{

Console.WriteLine("You entered a valid number: {0}", inputAsNumber);

}

else

{

Console.WriteLine("You entered an invalid number");

}

Console.ReadLine();

}






Re: Visual C# General C# User Input

Marky03

Thanks for your help! Smile




Re: Visual C# General C# User Input

Marky03

Just for future reference for readers reading this thread..I picked up a book today with another example.

int num;
Console.WriteLine("Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());


Either example is good. I just prefer to use this one ;-)

Marky03