C# 如何从控制台模拟用户输入?
我在HackerRank做一些挑战。我通常在visualstudio中使用C# 如何从控制台模拟用户输入?,c#,streamreader,windows-console,C#,Streamreader,Windows Console,我在HackerRank做一些挑战。我通常在visualstudio中使用windows窗体项目进行调试,但我意识到我在输入测试用例时浪费了很多时间。因此,我想建议一种可以轻松模拟console.ReadLine() 通常情况下,这些挑战的案例描述如下: 5 1 2 1 3 2 3 2 然后是这样读的:使用三个ReadLine 现在我正在考虑创建一个文件testCase.txt并使用StreamReader using (StreamReader sr = new StreamReader(
windows窗体
项目进行调试,但我意识到我在输入测试用例时浪费了很多时间。因此,我想建议一种可以轻松模拟console.ReadLine()
通常情况下,这些挑战的案例描述如下:
5
1 2 1 3 2
3 2
然后是这样读的:使用三个ReadLine
现在我正在考虑创建一个文件testCase.txt
并使用StreamReader
using (StreamReader sr = new StreamReader("testCase.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
这样我就可以用sr.ReadLine()
替换Console.ReadLine()
,但每次都需要打开一个文本编辑器,删除旧的大小写,复制新的大小写并保存文件
那么,有没有一种方法可以使用文本框,只需在文本框中复制/粘贴,并使用streamReader或类似于从文本框中读取的东西?您可以使用该类从
字符串而不是文件中读取。您接受的解决方案!没有真正模拟Console.ReadLine(),因此无法将其直接粘贴到HackerRank
我是这样解决的:
只需将该类粘贴到static Main方法上方或主类内的任何位置,即可隐藏原始System.Console
现在你的代码看起来是一样的!您可以在不更改代码的情况下测试任意数量的数据
注意:如果您需要更多复杂的Write或WriteLine方法,只需添加它们并将它们发送到原始系统。控制台(…args)只需设置应用程序参数:.NET是否为提供高级包装?这应该很容易。普通的“黑客”只需使用输入重定向。。。My.exe这并没有回答所问的问题。问题的关键在于避免使用包含用户输入的外部文件,而是能够将测试数据直接合并到代码中。不要介意这个答案不涉及任何编程问题,所以在这里是离题的。如果不是因为它几乎肯定不会为该网站上的答案库提供任何新的内容,它可能适合在superuser.com上回答一个问题。
using (StreamReader sr = new StreamReader("testCase.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
class Console
{
public static Queue<string> TestData = new Queue<string>();
public static void SetTestData(string testData)
{
TestData = new Queue<string>(testData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.TrimStart()));
}
public static void SetTestDataFromFile(string path)
{
TestData = new Queue<string>(File.ReadAllLines(path));
}
public static string ReadLine()
{
return TestData.Dequeue();
}
public static void WriteLine(object value = null)
{
System.Console.WriteLine(value);
}
public static void Write(object value = null)
{
System.Console.WriteLine(value);
}
}
//Paste the Console class here.
static void HackersRankProblem(String[] args)
{
Console.SetTestData(@"
6
6 12 8 10 20 16
");
int n = int.Parse(Console.ReadLine());
string arrStr = Console.ReadLine();
.
.
.
}