Multiple lines input from console in c#

五迷三道 提交于 2021-02-08 13:59:16

问题


I am trying to read some values in c# from console and then processing them. However i am stuck at a error.

The input from console is:

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

and so on. I do not know before hand the number of console inputs...How can i detect that user has stopped entering & store the input.

I tried using

string line;
while((line=Console.ReadLine())!=null)
{
  //but here it seems to be an infinite loop 
}

Any suggestions


回答1:


Your code looks for "end of console input" which is "Ctrl+Z" as covered in Console.ReadLine:

If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. This enables the user to prevent further keyboard input when the ReadLine method is called in a loop. The following example illustrates this scenario.

If you are looking for empty string as completion use String.IsNullOrWhiteSpace.

string line;
while(!String.IsNullOrWhiteSpace(line=Console.ReadLine()))
{
  //but here it seems to be an infinite loop 
}



回答2:


There's no way for you to know implicitly that the user has finished entering all their data. You would need some explicit entry from the user to tell you that no more data was coming.




回答3:


Line will never be null, that's why it's an infinite loop. You have to check for empty string or specific value like the letter q (for quit). I recommend you the following.

string line;
do
{
    //input code

    //Check for exit conditions
    line = Console.ReadLine();
} while (!String.IsNullOrWhiteSpace(line) || line.ToLower() != "q");



回答4:


this is more easier isn't it Example: i am adding inputs of each line to a list

        List<int> inA = new List<int>();
        var inp = Console.ReadLine();
        while (inp != string.Empty)
        {
            inA.Add(Convert.ToInt32(inp));
            inp = Console.ReadLine();

        }


来源:https://stackoverflow.com/questions/24338657/multiple-lines-input-from-console-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!