第一个Console.ReadLine()立即返回 [英] first Console.ReadLine() returns immediately

查看:64
本文介绍了第一个Console.ReadLine()立即返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个非常愚蠢的程序。

I am writing a really silly program.

我不知道为什么以下代码不起作用:

I have no idea why the following code won't work:

static void Main(string[] args){
        <Some silly code>
        Console.WriteLine("Please choose the lab you are working on:");
        int choose = Console.Read();
        <Some more silly code, including 1 Console.writeLine() call >

        Console.WriteLine("Enter the DB server location");
        string DBServer = Console.ReadLine();
        Console.WriteLine("Enter the DB name");
        string DBName = Console.ReadLine();
    }

当我运行程序时,它从不等待第一个ReadLine语句

When I run the program, it never waits for the first ReadLine statement

string DBServer = Console.ReadLine();

它立即打印两行

Enter the DB server location  
Enter the DB name

然后读取第二个ReadLine string DBName = Console.ReadLine();

And then reads the second ReadLine string DBName = Console.ReadLine();

当我检查输入表单时用户,它的确读取了第二个,但是第一个字符串为空。

有什么想法吗?

When I check the input form user, it indeed reads the second one well, but the first string comes out empty.
Any ideas?

推荐答案

这是因为您正在使用 Console.Read 角色,但将独自离开回车符。然后将由 ReadLine 拾取。

This is because you are using Console.Read which will reach a character but will leave the carriage-return after it alone. Which will then be picked up by ReadLine.

输入是流。当您输入单个字符然后按回车键时,流中将有2–3个字符(取决于系统):输入的字符和换行符。 Read 只是给您流中的下一个字符,而 ReadLine 会读取所有内容,直到下一个换行符为止。再次,从流。因此,您的 Read 会获取一个字符,而ReadLine已经找到下一个换行符,因此可以快乐地继续。

Input is a stream. When you are entering a single character and then hit return there are 2–3 characters in the stream (depending on the system): The character you entered and the line break. Read just gives you the next character in the stream, while ReadLine will read everything up to the next line break. Again, from the stream. So your Read fetches a character and ReadLine already finds the next line break and thus continues happily.

您可以选择插入一个哑元 ReadLine ,或使用 ReadKey ,它只会读取一个键,而在程序前不需要返回看到输入,或者也将 ReadLine 用作单字符输入。

You can either insert a dummy ReadLine, or use ReadKey which will just read a key and won't need a return before your program sees the input, or use ReadLine for the single-character input as well.

这篇关于第一个Console.ReadLine()立即返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆