tags:

views:

356

answers:

3

i am having trouble when i try to get user input of an array.. this is my code!!!. the problem is when i take input .. it does not store that specific value.. for exapmle if i take inout 1. it stores 48 and the while loop runs 3 time and then asks for the second input.. plz help!! following is my code!!run it and tell wats wrong..

using System;

class abc
{
    static void Main()
    {
        int[]a=new int[5];
        int b=0;
        int l=1;
        int I=1;

        Console.WriteLine("***************Taking User Input****************");
        while (l != 0)
        {

            Console.Write(I + ".");
            a[b] = Console.Read();
            l = a[b];
            b++;
            I++;
        }
    }
}
A: 

I'm not sure what do you want to do, but look below:



static void Main()
{
    int[]a=new int[5]; int b=0; int l=1; int I=1;
    while (l != 0)
    {
        Console.Write(I + ".");
        a[b] = Convert.ToInt32(Console.ReadLine());
        l = a[b];
        b++;
        I++;
    }
}
Rubens Farias
+1  A: 

Console.Read returns an integer corresponding to the key code. When you type the character "1" into the console, that doesn't translate to an integer 1 being returned from Console.Read().

You can also get rid of a bunch of your variables used for indexing:

        int[] a = new int[5];
        int i = 1;

        Console.WriteLine("***************Taking User Input****************");
        while (i <= a.Length)
        {
            Console.Write(i + ". ");
            a[i-1] = Convert.ToInt32(Console.ReadLine());

            if (a[i-1] == 0) break;  // escape while loop if user inputs "0"

            i++;
        }
Larsenal
plz explain briefly about Convert.ToInt32 i thought that for string we use simple console.readline and for integers we use read.. i didnt know about this convert code...as the book i am following does not cover that...
wahaab
A: 

plz explain briefly about Convert.ToInt32 i thought that for string we use simple console.readline and for integers we use read.. i didnt know about this convert code...as the book i am following does not cover that...

wahaab
Console.Read will return an integer code corresponding to an individual key press. So if you typed "123" that would be read as three individual keystrokes. So for example, a user might press an arrow button on the keyboard. You could use Console.Read to capture that. By using Console.ReadLine, we capture a whole line of input which may be several characters long. Then we take that whole string of characters and convert it into an integer. Make sense?
Larsenal
Correction... Console.Read reads the next character from the standard input stream... which is a bit different from each keystroke.
Larsenal
yes made some sense!!!i'll do more experiments!!!!for perfection!!!this is a lot of different than c++..thnx you for your help!!!appreciate you people replying in just a short while!!!
wahaab