0

I am having an issue with this block of code.

        Console.WriteLine("What is your name?");
        string PlayerName = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(PlayerName);

What I'm trying to do is get the computer to read the name you input, and ask you if that is your name. Directly after I type my name though there is an exception. Convert.ToInt32 isn't what I'm supposed to use, and I guess my question is what do I put there instead.

I am new to programming and I'm not even sure if it's called unicode. Sorry.

4 Answers4

2

Console.ReadLine() will return a string, no need to do any conversions:

    Console.WriteLine("What is your name?");
    string PlayerName = Console.ReadLine();
    Console.WriteLine(PlayerName);
Blam
  • 2,888
  • 3
  • 25
  • 39
2

Convert.ToInt32() throw casting error if you do not pass valid integer value inside it. So, you need to check it gracefully and get interger value. For that, you can Int32.TryParse(input, out val) and get integer value.

Ex :

int value;
if(Int32.TryParse(your_input, out value))
{
// if pass condition, then your input is integer and can use accordingly
}

So, your program will be like this if you want to print integer value only :

    Console.WriteLine("What is your name?");
    var value = Console.ReadLine();
    int intVal;
    if(Int32.TryParse(value, out intVal))
    {
        Console.WriteLine(intVal);
    }

If you want only to print what you've got from ReadLine method, you can just have :

  Console.WriteLine("What is your name?");
  Console.WriteLine(Console.ReadLine());
Akash KC
  • 16,057
  • 6
  • 39
  • 59
1

Convert.ToInt32(String) "Converts the specified string representation of a number to an equivalent 32-bit signed integer". You are getting an error because you are not typing in an integer value in your console.

Your PlayerName variable is of type string, and the return value of Console.ReadLine() is already a string, so you don't need any conversion.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70
0

If you’re dealing with Unicode characters, you might have to set proper encoding like so

Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;

Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);
Lumen
  • 3,554
  • 2
  • 20
  • 33