0

I was solving a problem which says that I have to take a character input and print it's ascii value.

I wrote a program like this which works fine.

using System;
namespace ASCII_Value
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            int i = Convert.ToInt32(s[0]);
            Console.WriteLine(i);
        }
    }
}

But is there a better way that I only take a character input because user can enter a sentence and will get ascii value of the first character which is senseless as it is stated in the problem statement that I should take in a character.

I want that user not to be able to enter more than one character.

Neuron
  • 5,141
  • 5
  • 38
  • 59
gamerdev
  • 65
  • 6
  • But it doesn't return a character so I cannot store it's value in a character variable. – gamerdev Nov 06 '17 at 18:13
  • static void Main(string[] args) { string s = Console.ReadLine(); byte[] asciiBytes = Encoding.ASCII.GetBytes(s); foreach(var ascii in asciiBytes){ Console.WriteLine(ascii); } } https://stackoverflow.com/questions/400733/how-to-get-ascii-value-of-string-in-c-sharp – Little Fox Nov 06 '17 at 18:17
  • Did you not click on the duplicate link? Start there and read the accepted answer, it has a code sample for returning the `char` for the key stroke. – Igor Nov 06 '17 at 18:26

0 Answers0