c# - 如何模拟来自控制台的用户输入?

标签 c# streamreader windows-console

我正在 HackerRank 中做一些挑战。我通常使用 Visualstudio 中的 windows Form 项目进行调试,但意识到我浪费了很多时间输入测试用例。所以我想要一种可以轻松模拟 console.ReadLine()

的建议

通常,挑战的案例描述如下:

5
1 2 1 3 2 
3 2

然后读取如下:使用三个 ReadLine

static void Main(String[] args) {
    int n = Convert.ToInt32(Console.ReadLine());
    string[] squares_temp = Console.ReadLine().Split(' ');
    int[] squares = Array.ConvertAll(squares_temp,Int32.Parse);
    string[] tokens_d = Console.ReadLine().Split(' ');
    int d = Convert.ToInt32(tokens_d[0]);
    int m = Convert.ToInt32(tokens_d[1]);
    // your code goes here
}

现在我正在考虑创建一个文件 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或类似的东西从文本框中读取?

最佳答案

您可以使用StringReader类从字符串而不是文件中读取。

关于c# - 如何模拟来自控制台的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727664/

相关文章:

c# - 多页 WIA 扫描(docfeeder)扫描 1 页并 block 扫描仪

c# - 创建多个表/网格

c# - 在上一个调用仍在进行时无法重新调用 BeginGetRequestStream/BeginGetResponse

c# - 无法打开运行 exe 生成的输出文件

c++ - 尝试执行任何需要它时无法修复 WinAPI 中的 "invalid handle"错误

c# - 在 C# 中使用 SqlTransaction,如何从存储过程中获取输出参数并插入到另一个表中?

c# - VCF Vcard 导入 c#

C# XNA - 读取 .txt 文件并创建二维数组

c++ - 控制台输出 - 让插入符跳转到列和行的方法

scheduled-tasks - 运行计划任务执行批处理文件时保持命令行窗口打开