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.


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.


Try to change your code in this way

int amount;
while(true)
{
    Console.WriteLine("How many students would you like to enter?"); 
    string number = Console.ReadLine(); 
    if(Int32.TryParse(number, out amount))
        break;
}
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); 
} 

Instead to use Read use ReadLine and then check if the user input is really an integer number using Int32.TryParse. If the user doesn't input a valid number repeat the question.
Using Console.Read will limit your input to a single char that need to be converted and checked to be a valid number.

Of course this is a brutal example without any error checking or any kind of safe abort from the loops.


For someone who might still need this:

static void Main(string[] args)
{
     Console.WriteLine("How many students would you like to enter?");
     var amount = Convert.ToInt32(Console.ReadLine());

     Console.WriteLine("{0} {1}", "amount equals", amount);

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