我的问题很简单,但是我似乎找不到一个简单的答案,就这一点而言根本没有答案。
我想要做的是打印一个问题,然后有一个答案字段,然后在不等待输入的情况下写出更多文本:
This is a program that solves second degree equations using this formula ax*x + bx + c = d
write your numbers! {WHERE I WANT TO WRITE AND GET INPUT}x*x + bx+ c = d
我{WHERE I WANT TO WRITE AND GET INPUT}
在应用程序运行时写了我想写的地方,然后获取了输入,因此应用程序可以开始做数学了!
注意:在控制台程序的上下文中,术语“光标”是指控制台文本的插入符号或插入点,而不是指您的鼠标指针。
您可以Console.SetCursorPosition
用来控制将文本写入控制台的位置,但是它带有许多警告:
即,您将需要使用Console.CursorTop
和Console.CursorLeft
(或Console.GetCursorPosition
在.NET 5上)获取当前光标位置。这样一来,您就可以在打印字段时知道光标在哪里-因为控制台缓冲区(其大小可以与窗口不同)可以在任何时候被用户调整大小-这也是为什么许多控制台程序输出乱码的原因调整大小时的文本(如果它们不能正确控制光标位置)。
这是您的问题的示例实现:数学表达式中的占位符。请注意,每个占位符只能插入单个字符(由下划线字符表示)。如果要使占位符随着输入更多数字而动态扩展,那么这是读者的一项练习(提示:使用来重新打印该行\r
)。
static void Main( string[] args )
{
const String line1 = "This is a program that solves second degree equations using this formula ax*x + bx + c = d";
const String line2 = "write your numbers! _x*x + _x+ _c = d";
// HACK:
if( Console.BufferWidth < line2.Length )
{
Console.WriteLine( "Please resize your console window to {0} columns and restart this program.", line2.Length );
return;
}
Console.WriteLine( line1 );
Console.WriteLine( line2 );
// Get the character indexes of the placeholders:
Int32 pos1 = line2.IndexOf( '_' );
Int32 pos2 = line2.IndexOf( '_', pos1 + 1 );
Int32 pos3 = line2.IndexOf( '_', pos2 + 1 );
Int32 pos4 = line2.IndexOf( 'd', pos3 + 1 );
#if NET5_0
(Int32 x, Int32 y) = Console.GetCursorPosition();
#else
Int32 x = Console.CursorLeft;
Int32 y = Console.CursorTop;
#endif
// Curiously, `y` is 2 for the second line (implying base 1), but SetCursorPosition uses base 0, so adjust it:
y = y - 1;
// Assuming the placeholders are on the same line without any wrapping:
Console.SetCursorPosition( left: pos1, top: y );
Int32? a = ReadDigit();
if( a == null ) return;
Console.SetCursorPosition( left: pos2, top: y );
Int32? b = ReadDigit();
if( b == null ) return;
Console.SetCursorPosition( left: pos3, top: y );
Int32? c = ReadDigit();
if( c == null ) return;
// Compute 'd':
Double d = 1234;// SolveQuadradicFormula( a, b, c );
// Move cursor where the 'd' is:
Console.SetCursorPosition( left: pos4, top: y );
// Then write the value of d:
Console.Write( d );
Console.WriteLine();
}
private static Int32? ReadDigit()
{
do
{
ConsoleKeyInfo key = Console.ReadKey();
if( Char.IsDigit( key.KeyChar ) )
{
return key.KeyChar - '0';
}
else if( key.Key == ConsoleKey.Escape )
{
return null;
}
}
while( true );
}
屏幕截图证明:
等待用户输入:
按下1
键盘后:
然后,在按下2
键盘后:
然后,按下3
我的键盘(它也显示的值d
,这只是1234
:现在是假的占位符值):
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句