1

I am trying to hold integer inputs into an array but it doesn't work. I found an example for string hold from How to Fill an array from user input C#?

string[] yazi = new string[15];
for (int i = 0; i < yazi.Length; i++)
{
      yazi[i] = Console.ReadLine();
}

But when I turn this code to integer, it gave an error

int[] sayis = new int[20];
for (int k = 0; k < sayis.Length; k++)
{
      sayis[k] = int.Parse(Console.ReadLine());
}

Am I missing something?

halfer
  • 19,824
  • 17
  • 99
  • 186
Merve Gül
  • 1,377
  • 6
  • 23
  • 40

1 Answers1

6

Am I miss something?

The error message, for one thing...

It should be fine - so long as you type integers into the console. (I've just tried it, and it worked perfectly.) If the user enters a value which can't be parsed as an integer, you'll get a FormatException. You should consider using int.TryParse instead... that will set the value in an out parameter, and return whether or not it actually succeeded. For example:

for (int k = 0; k < sayis.Length; k++)
{
    string line = Console.ReadLine();
    if (!int.TryParse(line, out sayis[k]))
    {
        Console.WriteLine("Couldn't parse {0} - please enter integers", line);
        k--; // Go round again for this index
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But I got the error, which I didnt give any input to the console. I mean, I get error when the console run. I will try int.TryParse – Merve Gül Mar 31 '12 at 10:15
  • @Merve: Right. That will happen if you don't type in a number (including if you press return without entering anything). – Jon Skeet Mar 31 '12 at 10:23