I'm getting different user input instead of getting real inputs given by user in codechef
User Input:
4
1 2 3 4
Expected Output: 4 3 2 1
using System;
public class Test
{
public static void Main()
{
int N = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[N];
for(int i=0;i<N;i ){
arr[i] = Convert.ToInt32(Console.Read());
}
for(int j=N-1;j>=0;j--){
Console.Write(arr[j]);
Console.Write(" ");
}
}
}
Output I got: 32 50 32 49
CodePudding user response:
Since you said you want to do it without ReadLine
, let's work with your current code. There are two issues at hand.
- You should skip the spaces
- You get the character codes instead of the values
To skip the spaces, you can simply read them and do nothing with the read character. I implemented this below in a way that assumes after every number (one digit long) there will be a single space to ignore. But you could also do that in a less hacky way by checking what the read character actually is before you discard it.
To get the character code into the value, I first perform a conversion into a char
by casting it. Then I get the numeric value, which might be a double
. But because you know that your numbers are integers, we can cast that to int
.
using System;
class Program {
static void Main(string[] args) {
int N = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[N];
for(int i=0;i<N;i ){
arr[i] = (int)Char.GetNumericValue((char)Console.Read());
Console.Read();
}
for(int j=N-1;j>=0;j--){
Console.Write(arr[j]);
Console.Write(" ");
}
}
}