Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple lines input from console in c#

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

like image 560
user3762206 Avatar asked Jun 21 '14 05:06

user3762206


2 Answers

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 
}
like image 182
Alexei Levenkov Avatar answered Sep 24 '22 19:09

Alexei Levenkov


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.

like image 26
jmcilhinney Avatar answered Sep 23 '22 19:09

jmcilhinney