简体   繁体   中英

Converting an int to a Char c#?

I want to be able to Read a value from the operator M/F for male or female and return seperate blocks of text for each respective entry.

Char gender;
int TempValue;
Console.WriteLine("Please enter your name");
Console.CursorVisible=true;
String name = Console.ReadLine();
Console.WriteLine(" Greetings, faire travler {0} you are about to depart on a rather exciting adventure, but first are you male or female?", name);
Console.WriteLine("(M/F)");

TempValue = Console.Read();
Console.WriteLine("{0}", TempValue);
gender = Char.Parse(TempValue);

Now i get an error saying I "cannot convert from 'INT' to 'string' which I really dont understand. Becuase im trying to parse it into a char not a string.

Char.Parse takes a string as it's parameter, but TempValue is declared as an int . You can either ToString TempValue :

gender = Char.Parse(TempValue.ToString());

or use Convert.ToChar() , which takes an object :

gender = Convert.ToChar(TempValue);

Console.Read() returns the ascii value of the character you entered. (In case of 'M' it's 77) char.Parse(TempValue) expects TempValue to be a string and that it contains exactly one character. So, this is what you would use to convert the string "M" to the character 'M'. But you don't have the string "M"; you have the int 77.
In this case, you can simply cast it:

char gender = (char)TempValue;

Alternatively, you can use Console.ReadLine() , which returns a string and then take the first character:

string input = Console.ReadLine();
char gender = input[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM