简体   繁体   中英

C# Console : How can i enter a value in LastName after i Enter a variable in the char variable?

Here's my code:

public static void Main(string[] args) 
{
  string FirstName;
  string LastName;

  char MiddleInitial;

  Console.Write("Enter  first name: ");

  FirstName = Console.ReadLine();

  if (FirstName.Equals("null")) 
  {
    Console.Write("Insert middle initial: ");
    Console.Write("\n Insert last name: \n");
  } 
  else 
  {
    Console.Write("Insert middle initial: ");

    MiddleInitial = (char) Console.Read();

    Console.Write("Enter  last name: ");

    LastName = Console.ReadLine();

    Console.ReadKey();
  }

}

I can't enter the lastname variable at the last part of my code. Anyone there more knowledgable who can answer my concern?

The output always went like this: Enter first name:Jason Insert middle initial: f Enter last name:

After i press one letter it goes back to the IDE

The program output should be like this:

Enter  first name:Joshua 

Insert middle initial:F

Enter  last name:Capili

Enter  first name:null 
Insert middle initial:
Enter  last name:

I try to execute your code, in my VS it works. Try this code:

 MiddleInitial = Console.ReadKey().KeyChar;

Or this:

 MiddleInitial = Console.ReadLine()[0];

This is happening because Console.Read() appends a new line to the input . When you subsequently do Console.Readline() there is already a line in the buffer so it sets LastName to whatever comes after the first character you type, even if it is empty string.

You can use ReadLine() for the middle initial (as a string) and just take the first character.

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