0

I am quite new to c#, and still don't understand some basics about arrays. When I initialize my program, I ask the user for an input, in integer form, and then I use that to declare the size of the array. Implementation:

int sortSpaceSize = Console.Read ();
bool[] sortSpace = new bool[sortSpaceSize];

However, when I test the program, the array size is just...wierd. When I type 45 as an input, it outputs an array size of 52. With 964684, it outputs 57. I have no idea on what is wrong. If you are not allowed to use variables as sizes when declaring arrays, then why does this not throw an error? Should I use a list instead? Thank you in advance.

  • `Should I use a list instead?` That's not the cause of your error, but you almost certainly should, yes. – Servy Jan 16 '17 at 18:51
  • `Console.Read();` only reads one character. Change `Console.Read();` to `Convert.ToInt32(Console.ReadLine();)`. – Yousaf Jan 16 '17 at 18:53

1 Answers1

1

That's because you are only reading one char. Try reading a complete number:

string input = Console.ReadLine();
int sortSpaceSize;
if (!Int32.TryParse(input, out sortSpaceSize))
{
    throw new Exception("not a number");
}
bool[] sortSpace = new bool[sortSpaceSize];

As Chris made it clear why you get those strange numbers: you are converting the ascii code of the first digit and used that as your array size.

Nico
  • 3,542
  • 24
  • 29
  • 2
    Yup. And to clarify with 45 as an input the array size is 52 which is the ascii code for `4`. Likewise 57 is the ascii code for `9`, the first character of 964684. – Chris Jan 16 '17 at 18:53
  • As a comment on code it is probably worth either checking the return of `TryParse` if you think it might fail or if you don't expect it to fail just use `Int.Parse`. If you use `TryParse` and then throw away the success you may end up hiding errors (eg if the person types "blah" instead of a number then `sortSpaceSize` will probably end up as 0. – Chris Jan 16 '17 at 18:57