简体   繁体   中英

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?

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
    }
}

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.

if I ve understood you correct...

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

Smth like that...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM