Int input from Console

  • Thread starter Thread starter =?iso-8859-1?B?QWRyaeFuIEUuIEPzcmRvYmE=?=
  • Start date Start date
?

=?iso-8859-1?B?QWRyaeFuIEUuIEPzcmRvYmE=?=

Sorry for very silly question.
But, how can I input an integer from keyboard in C# Console
applications?
Like this, in C++ code:
"int i ; cin >> i ;"
I just read some tutorials about C#, and I can get a "string" from
keyboard, but I can't get an integer.

Thank you in advance.
 
Adrián E. Córdoba said:
But, how can I input an integer from keyboard in C# Console
applications?
Like this, in C++ code:
"int i ; cin >> i ;"
I just read some tutorials about C#, and I can get a "string" from
keyboard, but I can't get an integer.

int v = int.Parse(Console.ReadLine());

was at least one way.

Arne
 
Hi,

quick , dirty code :)

int i=0;
while( true )
{
try {
i = Convert.ToInt32( Console.ReadLine() );
break;
}catch{
Console.WriteLine( "Invalid number");
}
}
 
Ignacio said:
You may get an exception if what you read is not a number

Yep.

The original poster should catch the exception and
so something appropriate if that happen.

Arne
 
For your information:
I found in a tutorial, a compact expression for Integer input:

int i = Convert.ToInt32(Console.ReadLine());

Thank you again.
Best regards.
 
Adrián E. Córdoba said:
For your information:
I found in a tutorial, a compact expression for Integer input:

int i = Convert.ToInt32(Console.ReadLine());

To quote from docs for Convert.ToInt32:

Remarks
The return value is the result of invoking the Int32.Parse method on value.

Arne
 
Back
Top