【问题标题】:why same msdn C# sample program output is not same as mine? [closed]为什么相同的 msdn C# 示例程序输出与我的不同? [关闭]
【发布时间】:2013-01-07 20:40:35
【问题描述】:

这是一个初学者类型的问题,我很抱歉我的英语不好。

这是程序:

using System;
public class BoolTest 
{
    static void Main() 
    {
        Console.Write("Enter a character: "); 
        char c = (char)Console.Read();
        if (Char.IsLetter(c))
        {
            if (Char.IsLower(c))
            {
                Console.WriteLine("The character is lowercase.");
            }
            else
            {
                Console.WriteLine("The character is uppercase.");
            }
        }
        else
        {
            Console.WriteLine("Not an alphabetic character.");
        }
    }
}

MSDN 输出是:

输入一个字符:X

字符是大写的。

其他示例运行可能如下所示:

输入一个字符:x

字符是小写的。

输入一个字符:2

该字符不是字母字符。

我的输出没有说明这个版本的代码。如果我在 if 语句之前添加了一个 while(1==1) 行,我会采用三行输出,例如:

输入一个字符:X

字符是大写的。

该字符不是字母字符。

该字符不是字母字符。

输入一个字符:x

字符是小写的。

该字符不是字母字符。

该字符不是字母字符。

输入一个字符:2

该字符不是字母字符。

该字符不是字母字符。

该字符不是字母字符。

我尝试了 else 语句的 Console.ReadLine() 结尾,但不起作用。我还用 while (1==1) 测试了 else 块的注释,我只得到 1 个输出行..

我想知道为什么对于相同的示例代码,输出包含 3 行?

【问题讨论】:

  • 您的项目是否设置为控制台应用程序?
  • 是的,这是作为控制台应用程序创建的
  • 您是否在字符之间按下enter 按钮?如果是这样,那实际上是两个非字母字符。
  • 非常感谢史蒂夫,这实际上是我的回答..

标签: c# boolean


【解决方案1】:

我的第一个答案是错误的 - Console.Read() 块。从 Visual Studio 运行程序时,您可能只是错过了输出,因为窗口会立即关闭。只需在程序末尾附加两次Console.ReadLine(); 即可保持窗口打开。第一个Console.ReadLine(); 将消耗你在字符后按下的回车,第二个将等到你再次按下回车,因此保持窗口打开。

或者稍微修改一下程序使用Console.ReadKey()——使用

var c = Console.ReadKey().KeyChar;

// Insert a line break to get the output on a new line.
Console.WriteLine();

并在程序末尾添加一个Console.ReadLine();Console.ReadKey() 不会阻塞,直到您按回车键,因此无需使用第二个 Console.ReadLine(); 消耗新行。

原答案

Console.Read() 不会阻塞,如果没有可用字符,将立即返回 -1。你可以插入

while (!Console.KeyAvailable) { }

就在之前

 char c = (char)Console.Read();

等到一个字符可用。

【讨论】:

  • 最好只使用 Console.ReadKey() which blocks,而不是添加 spinwait。
  • 我错了 - 它实际上会阻塞,直到您按 Enter 键。我必须重新阅读文档。
猜你喜欢
  • 2020-10-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2019-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多