问题描述:

How can I take input in an array in c#.I have written a code it's not working right. For example, if I input 1, then it gives an output 49.

using System;

using System.Collections.Generic;

using System. Linq;

using System.Text;

using System.Threading.Tasks;

namespace Google

{

class Program

{

static void Main(string[] args)

{

int n;

int[] array=new int[26];

Console.Write("Enter number of cases : ");

n = Console.Read();

for (int i = 0; i < n; i++)

{

array[i] = Console.Read();

Console.WriteLine( array[i]);

}

Console.Read();

}

}

}

网友答案:

Console.Read method gets the next character from input stream, and converts it to integer value which is the ASCII value of the char. You want Console.ReadLine instead:

array[i] = int.Parse(Console.ReadLine());

Use int.TryParse if you want to validate user's input.


Btw it can be done with Read method if you want to get just numbers from 0 to 9 (which probably you don't), but the code will look ugly:

 array[i] = int.Parse(((char)Console.Read()).ToString());
网友答案:

Console.Read returns the character code, not the number you entered.

Use int.Parse(Console.ReadLine()) instead:

n = int.Parse(Console.ReadLine());
//...
array[i] = int.Parse(Console.ReadLine());
网友答案:

49 is correct. this number is coming for the ascii value of the character "1" Source (http://www.asciitable.com/)

You need to include a parser for your int.

As Selman22 said:

array[i] = int.Parse(Console.ReadLine());

will work for you.

网友答案:

You are reading a char, not a number, in your case it is returning the ASCII value of 1, which is 49. You should use proper parsing functions like Int32.Parse(Console.ReadLine()).

网友答案:

1 coming across as 49 should be your hint. 49 is the ASCII value for the character '1'.

So what's happening is that your Console.Read() call is returning a char which is being implicitly cast as an integer into your integer array.

You probably actually expect the user to type a number and hit enter. So you'd probably be better off using Console.ReadLine() and then using int.TryParse on the string you get from that.

相关阅读:
Top