Md Johirul Islam
Md Johirul Islam

Reputation: 874

Reading integers from console in C#

Please look at the following C++ code and help me to do the same in c#

for(int i=0;i<10;i++)
{
 cout<<"Enter a["<<i<<"]=";
 cin>>a[i];
}

I tried to implement the same loop in C# for taking integer input but it ended with exception like following

for(int i=0;i<10;i++)
{
a[i]=Int32.Parse(Cosole.Read());
}

Can anyone help me to implement that loop in C#? The parse work one time but it doesn't work inside loop. Whats the problem?

Upvotes: 0

Views: 2521

Answers (3)

herohuyongtao
herohuyongtao

Reputation: 50657

Console.Read() only reads the next character from the standard input stream, which will not work if you want to read 32 as an integer. You better use Console.ReadLine() instead:

for (int i=0; i<10; i++)
{
    string line = Console.ReadLine();
    int value;
    if (Int32.TryParse(line, out value))
    {
       a[i] = value;
    }
    else
    {
        // cannot parse it as an integer
    }
}

Upvotes: 2

Baranovskiy Dmitry
Baranovskiy Dmitry

Reputation: 463

if I ve understood you correct...

for(...)
{
    Console.WriteLine(string.Format("Enter a {0}"),i);
    a[i] = Convert.ToInt32(Console.ReadKey());
}

Smth like that...

Upvotes: 0

Christos
Christos

Reputation: 53958

Try this one:

int[] a = new int[10];
for(int i=0;i<10;i++)
{
    Console.WriteLine("Enter a[{0}]=",i);
    a[i]=Int32.Parse(Console.ReadLine());
}

Pleace check this fiddle.

Upvotes: 1

Related Questions