![](/img/trans.png)
[英]c# Console Application How to enter multiple lines of input and not just take the first line in ReadLine?
[英]Multiple lines input from console in c#
我试图从控制台读取 c# 中的一些值,然后处理它们。 但是我遇到了错误。
控制台的输入是:
Name:ABCD
School:Xyz
Marks:80
//here the user enters a new line before entering new data again
Name:AB
School:Xyz
Marks:90
//new line again
Name:AB
School:Xyz
Marks:90
等等。 我事先不知道控制台输入的数量...如何检测用户已停止输入和存储输入。
我尝试使用
string line;
while((line=Console.ReadLine())!=null)
{
//but here it seems to be an infinite loop
}
有什么建议
您的代码查找“控制台输入结束”,即Console.ReadLine 中所述的“Ctrl+Z”:
如果在方法从控制台读取输入时按下 Ctrl+Z 字符,则该方法返回 null。 这使用户能够在循环调用 ReadLine 方法时阻止进一步的键盘输入。 以下示例说明了这种情况。
如果您正在寻找空字符串作为补全,请使用String.IsNullOrWhiteSpace 。
string line;
while(!String.IsNullOrWhiteSpace(line=Console.ReadLine()))
{
//but here it seems to be an infinite loop
}
您无法隐含地知道用户已完成所有数据的输入。 您需要来自用户的一些明确输入来告诉您没有更多数据即将到来。
Line 永远不会为null
,这就是为什么它是一个无限循环。 您必须检查空字符串或特定值,例如字母q
(用于退出)。 我向您推荐以下内容。
string line;
do
{
//input code
//Check for exit conditions
line = Console.ReadLine();
} while (!String.IsNullOrWhiteSpace(line) || line.ToLower() != "q");
你可以这样做
var input = Console.In.ReadToEnd();
注意事项
这更容易不是吗 示例:我将每一行的输入添加到列表中
List<int> inA = new List<int>();
var inp = Console.ReadLine();
while (inp != string.Empty)
{
inA.Add(Convert.ToInt32(inp));
inp = Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.