Abhishek Jain
Abhishek Jain

Reputation: 493

integer value gets wrong in C#

The code is as follows. When I enter the value of t=2 in console,it gets printed as 50 and similarly it prints 51,52 for 3,4 and so forth.

class Program
    {
        static void Main(string[] args)
        {
            int h = 0;
            int t = 0;
            Console.WriteLine("Hello India!!");
            Console.WriteLine("Enter the no. of test cases");

            t= Convert.ToInt32(Console.Read());
            Console.WriteLine(t);

            for (int n = 1; n < t;n++ )
            {
                 Console.WriteLine("Enter the String");
                 String str = Console.ReadLine();

                for (int i = 0; i < str.Length; i++)
                {
                if ((str[i] == 'A') || (str[i] == 'D') || (str[i] == 'O') || (str[i] == 'P') || (str[i] == 'Q') || (str[i] == 'R'))
                    h = h + 1;
                else if (str[i] == 'B')
                    h = h + 2;
                else
                    continue;
                }
                Console.WriteLine(h);
         } 

        }
    }

Upvotes: 0

Views: 975

Answers (3)

Electric Coffee
Electric Coffee

Reputation: 12104

enter image description here

If you look closely on this table, you'll see that the symbol for '2' actually has the value 50

Console.Read() returns an integer, more specifically it returns an integer representing the first character you put in, so say I put in a, Console.Read() will spit out 97, if I input A it'll give me 65 and if I write AB it'll ALSO give me 65 because it reads the first char in the stream, and returns its integer value

Instead what you should do, is use Console.ReadLine() it takes any input, and returns it as a string, which you can then parse to an integer, so if I give it 2 it'll return "2" which you can then run through Convert.ToInt32() and get an integer out of.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283624

ASCII code of '2' is 50, and so on.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564333

You need to use Console.ReadLine(), not Console.Read(). This will return a string which will convert to the number 2 properly.

t = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(t);

Upvotes: 5

Related Questions