Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C中控制台输入的奇怪问题#_C#_Wpf_Console - Fatal编程技术网

C# C中控制台输入的奇怪问题#

C# C中控制台输入的奇怪问题#,c#,wpf,console,C#,Wpf,Console,在使用Console.Read()时,实现似乎认为只要按enter键,就已经输入了足够的字节,可以进行长时间的读取。例如,如果一行中调用了两次Read,则不能在一行中输入一个值,按enter键,然后移动到下一行。即使只输入了一个字符,Read也只返回零(Edit:或1,我不太确定)。我的ReadLine也有这个问题。我试图在程序终止后(我有一个WPF应用程序,并手动使用AllocConsole)和/或提示用户输入每个单独的片段,保持控制台打开以供输入。但它不起作用。如果没有可用的输入,是否有按钮

在使用Console.Read()时,实现似乎认为只要按enter键,就已经输入了足够的字节,可以进行长时间的读取。例如,如果一行中调用了两次Read,则不能在一行中输入一个值,按enter键,然后移动到下一行。即使只输入了一个字符,Read也只返回零(Edit:或1,我不太确定)。我的ReadLine也有这个问题。我试图在程序终止后(我有一个WPF应用程序,并手动使用AllocConsole)和/或提示用户输入每个单独的片段,保持控制台打开以供输入。但它不起作用。如果没有可用的输入,是否有按钮要求它阻止

我编写了一个Brainfuck解释器,来自Wiki的示例程序如果不使用输入,就会产生预期的结果


我要做的是输入一个字符,按enter键,将该字符作为字符,然后重复。

在上次编辑后,我希望下面的代码可能提供您想要的内容,或者为您指明正确的方向

public static int ReadLastKey()
{
  int lastKey = -1;
  for(;;)
  {
    ConsoleKeyInfo ki = Console.ReadKey();
    if (ki.Key != ConsoleKey.Enter)
    {
      lastKey = (int)ki.KeyChar;          
    }
    else
    {
      return lastKey;
    }
  }       
}
函数ReadLastKey将读取按键笔划,并返回按enter键时最后按下的键

当然,如果不希望录制多个按键,可以删除循环,只需使用Console.ReadKey两次,一次获得按键,然后第二次等待enter键。或者其中一个的一些排列

这是该功能的一个简单版本,只允许按一次键,然后等待按enter键。注意这是非常简单的,您可能需要处理其他退出条件等

public static int ReadLastKey()
{
  int lastKey = -1;
  ConsoleKeyInfo ki;

  // Read initial key press
  ki = Console.ReadKey();

  // If it is enter then return -1
  if (ki.Key == ConsoleKey.Enter) return lastKey;

  lastKey = (int)ki.KeyChar;

  // Wait for the user to press enter before returning the last key presss,
  // and do not display key the errant key presses.
  do
  {
    ki = Console.ReadKey(true);
  } while (ki.Key != ConsoleKey.Enter);

  return lastKey;      
}

你能分享一些代码吗?Console.ReadLine应该在按下enter键之前接受输入,然后一个后续的Console.ReadLine将在按下enter键之前接受进一步的输入。但是我会有一个字符串。Read返回一个int。那么您想一次读取一个键吗?如果是这样的话,Console.ReadKey可能就是你想要的吗?@Chris Taylor:那更糟糕,因为输入在两个字符后终止(不需要输入!)而且你永远不能改变你将要输入的内容。你上一次的编辑使你的需求更加清晰。第一个功能对我来说已经足够好了——这不是一个专业的项目。当我需要更好的东西时,我可以在cout上使用C++/CLI包装器。