如何检查标准输入是否为空?

问题描述 投票:0回答:8

我需要知道标准输入中是否有输入符号。

但我不知道如何检查这样的情况。

据我了解,我无法使用 Console.Read() 因为它实际上会读取下一个输入符号。

c# console
8个回答
3
投票

我认为你可以使用

Console.In
作为
System.IO.TextReader
并使用
Peek()
-方法:

if(Console.In.Peek() == "I don't know what it will be...")
{ /* Do something */ }

2
投票
console.writeline();
var a = console.readline();
if(a == null)
{
do something..
}
else
{
do something..
}

2
投票
if(Console.In.Peek()!=-1) //solves the problem

1
投票

如果您想检查控制台的标准输入上是否有任何数据正在等待而不实际读取它,我建议您使用这样的方法:

using (var sr = new StreamReader(Console.OpenStandardInput()))
{
    //check if there are any characters on the input stream
    if(!sr.EndOfStream)
    {
        //do whatever You want to do when the stream is not empty
    }
    else
    {
        //do whatever You want to do when the stream is empty
    }
}

0
投票

我希望我理解你的问题,你可以尝试这样的事情:

var userInput = Console.ReadLine();
if (string.IsNullOrEmpty(userInput))
{
 // do stuff here
}

0
投票

也许这会有所帮助:

 string s = Console.ReadLine();
   if (s.Contains('@') Or s.Contains('!')) // you can add other symobols as need
   {
   //do your work

   }

0
投票

如果您想检查用户插入的输入类型,那么如果您的 symbols 指的是 "<,>,?,/,@,#,$,%,^,& 等,则可以使用类似的内容。 ..” 这些链接可以帮助您解决输入字段的验证这个

请正确提出您的问题,很难理解什么 你在问


0
投票

如果您正在编写一个 C# 控制台应用程序来支持管道输入,并且想要检查是否有管道输入而不阻塞,您将需要使用:

Console.IsInputRedirected

例如,请参阅以下内容:

Console.WriteLine(Console.IsInputRedirected); //checks for piped input without blocking

if (Console.IsInputRedirected) //checks for piped input without blocking
{
    var stdin = Console.ReadLine(); //reads the piped input without blocking
    Console.WriteLine($"piped input: {stdin}");
}
else
{
    Console.Write("prompt: ");
    var stdin = Console.ReadLine(); //blocks because there is no piped input
    Console.WriteLine($"prompted input: {stdin}");
}

如果有管道输入,上面将立即从管道输入中读取。

或者,如果没有输入通过管道传输到标准输入,则将阻止并从提示中读取。

© www.soinside.com 2019 - 2024. All rights reserved.