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?

2
  • Works fine for me as long as I enter integers. What error do you get? Commented Mar 31, 2012 at 10:10
  • 1
    Input string was not in a correct format Commented Mar 31, 2012 at 10:22

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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: Right. That will happen if you don't type in a number (including if you press return without entering anything).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.