[英]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: output 总是这样: 输入名字:Jason 插入中间名首字母:f 输入姓氏:
After i press one letter it goes back to the IDE
The program output should be like this:程序output应该是这样的:
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.我尝试执行您的代码,在我的 VS 中它有效。 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 .发生这种情况是因为
Console.Read()
将新行附加到 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.当您随后执行
Console.Readline()
时,缓冲区中已经有一行,因此它将LastName
设置为您键入的第一个字符之后的任何内容,即使它是空字符串也是如此。
You can use ReadLine()
for the middle initial (as a string) and just take the first character.您可以将
ReadLine()
用于中间首字母(作为字符串)并只取第一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.