Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.Read() and Console.ReadLine() problems [duplicate]

I have been trying to use Console.Read() and Console.ReadLine() in C# but have been getting weird results. for example this code

Console.WriteLine("How many students would you like to enter?");
int amount = Console.Read();
Console.WriteLine("{0} {1}", "amount equals", amount);

for (int i=0; i < amount; i++)
{
     Console.WriteLine("Input the name of a student");
     String StudentName = Console.ReadLine();
     Console.WriteLine("the Students name is " + StudentName);
}

has been giving me that amount = 49 when I input 1 for the number of students, and Im not even getting a chance to input a student name.

like image 876
Mike Cornell Avatar asked Sep 06 '12 20:09

Mike Cornell


1 Answers

This because you read a char. Use appropriate methods like ReadInt32() that takes care of a correct conversion from the read symbol to the type you wish.

The reason why you get 49 is because it's a char code of the '1' symbol, and not it's integer representation.

char     code
0 :      48
1 :      49
2:       50
...
9:       57

for example: ReadInt32() can look like this:

public static int ReadInt32(string value){
      int val = -1;
      if(!int.TryParse(value, out val))
          return -1;
      return val;
}

and use this like:

int val = ReadInt32(Console.ReadLine());

It Would be really nice to have a possibility to create an extension method, but unfortunately it's not possible to create extension method on static type and Console is a static type.

like image 142
Tigran Avatar answered Sep 19 '22 20:09

Tigran