我需要知道标准输入中是否有输入符号。
但我不知道如何检查这样的情况。
据我了解,我无法使用 Console.Read() 因为它实际上会读取下一个输入符号。
我认为你可以使用
Console.In
作为 System.IO.TextReader
并使用 Peek()
-方法:
if(Console.In.Peek() == "I don't know what it will be...")
{ /* Do something */ }
console.writeline();
var a = console.readline();
if(a == null)
{
do something..
}
else
{
do something..
}
if(Console.In.Peek()!=-1) //solves the problem
如果您想检查控制台的标准输入上是否有任何数据正在等待而不实际读取它,我建议您使用这样的方法:
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
}
}
我希望我理解你的问题,你可以尝试这样的事情:
var userInput = Console.ReadLine();
if (string.IsNullOrEmpty(userInput))
{
// do stuff here
}
也许这会有所帮助:
string s = Console.ReadLine();
if (s.Contains('@') Or s.Contains('!')) // you can add other symobols as need
{
//do your work
}
如果您正在编写一个 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}");
}
如果有管道输入,上面将立即从管道输入中读取。
或者,如果没有输入通过管道传输到标准输入,则将阻止并从提示中读取。