试图让命令窗口不要消失

时间:2014-12-23 04:36:11

标签: c#

我是C#的新手。所以请帮我解决这个疑问。

当我运行此代码时,屏幕将暂停并等待输入。

    namespace HelloWorld1
    {
        class Program
        {
            static void Main(string[] args)
            {
                //int x=2;
                Console.WriteLine("Hello world! Enter an int.");
                Console.Read();
               /* x=Console.Read();
                Console.WriteLine("you've entered: " + x + " .");
                Console.ReadLine();
                */
            }
        }
    }

但是当我将代码更改为下面时,屏幕不再暂停......:

namespace HelloWorld1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x=2;
            Console.WriteLine("Hello world! Enter an int.");
            //Console.Read();
            x=Console.Read();
            Console.WriteLine("you've entered: " + x + " .");
            Console.Read();
        }
    }
}

为什么会这样?

编辑:

最新代码(仍然没有暂停屏幕):

namespace HelloWorld1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x=2;
            Console.WriteLine("Hello world! Enter an int.");
            x=Console.Read();
            Console.WriteLine("you've entered: " + x + " .");
            Console.ReadLine();
        }
    }
}

4 个答案:

答案 0 :(得分:5)

使用Read()方法的目的是什么? documentation:“返回输入流中的下一个字符,如果当前没有要读取的字符,则返回负数(-1)。...对Read方法的后续调用将检索输入的一个字符在检索到最后一个字符后,Read再次阻止其返回并重复循环。“

改为使用Readline()。

答案 1 :(得分:3)

使用Debug菜单中的'Start without Debugging'模式(Ctrl+F5)运行您的控制台应用程序。

  

如果您运行带有普通旧F5的控制台应用程序,控制台窗口会在屏幕上闪烁并消失,除非您在代码中添加Console.ReadLine;使用Control_F5,控制台窗口保持在屏幕上,直到您按下Return键。

来源:Visual Studio Tip: The Difference Between Start Without Debugging and Start with Debugging

答案 2 :(得分:1)

Console.Read()基本上会读取一个字符,所以如果你在控制台上按一个键,控制台就会关闭,同时Console.Readline()将读取整个字符串并从输入中返回下一行字符stream,如果没有更多行可用,则返回null。在代码的第一部分,控制台等待按下一个键,这就是窗口挂起的原因。为了实现您的目标,我建议Console.ReadKey()方法,它获取用户按下的下一个字符或功能键。按下的键显示在控制台窗口中,如here所述。

答案 3 :(得分:1)

当您使用Read函数时,它只返回下一个字符,该字符在缓冲区中保留换行符(从您按Enter键时)。然后当您调用ReadLine时,它会自动读取左侧的换行符,然后关闭应用程序。使用ReadLine获取你的int并转换它:

int x = 2;
Console.WriteLine("Hello world! Enter an int.");

x = int.Parse(Console.ReadLine()); //Change this line right here

Console.WriteLine("you've entered: " + x + " .");
Console.ReadLine();