Reputation: 874
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
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
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