2016-11-06 57 views
1

我做的C#解析在控制檯應用程序粘貼的文本

控制檯應用程序,它允許用戶在一定的文本粘貼如下

aaaaa 
bbbbb 
ccccc 

我知道到Console.ReadLine()不會把它,所以我二手console.in.readtoend()

  string input = Console.In.ReadToEnd(); 

      List<string> inputlist = input.Split('\n').ToList(); 

我需要它由線 上面的代碼工作來解析輸入文本行,但粘貼後,爲了conintue,用戶必須按下回車鍵一次,然後按ctrl + z然後再次進入。

我想知道是否有更好的方式來做到這一點 一些需要只需要敲擊回車鍵一次

有什麼建議?

謝謝

回答

2

在控制檯中,如果粘貼一行代碼塊,它們不會立即執行。那就是如果你粘貼

aaaa 
bbbb 
cccc 

什麼也沒有發生。一旦你進入,閱讀方法開始做它的工作。 ReadLine()在每一行後都會返回。所以我一直做的方式,以及國際海事組織這是最簡單的方法:

List<string> lines = new List<string>(); 
string line; 
while ((line = Console.ReadLine()) != null) 
{ 
    // Either you do here something with each line separately or 
    lines.add(line); 
} 
// You do something with all of the lines here 

我的第一個計算器的回答,我感到興奮。

+0

嗨這實際上工作,只是再試一次!謝謝你,並祝賀你的第一個被接受的答案!大聲笑 – ikel

0

我現在明白爲什麼這個問題很難。這對你有用嗎?

Console.WriteLine("Ctrl+c to end input"); 
StringBuilder s = new StringBuilder(); 
Console.CancelKeyPress += delegate 
{ 
    // Eat this event so the program doesn't end 
}; 

int c = Console.Read(); 
while (c != -1) 
{ 
    s.Append((char)c); 
    c = Console.Read(); 
} 

string[] results = s.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); 
+0

不,這不會做,因爲它會在第一行後運行,並忽略其餘行 – ikel

+0

更改我原來的答案(這肯定沒有工作) – fancycat

0

你不需要做任何額外的事情。只需通過ReadLine讀取,然後按回車。

string line1 = Console.ReadLine(); //aaaaa 
string line2 = Console.ReadLine(); //bbbbb 
string line3 = Console.ReadLine(); //ccccc 
+0

好吧,問題是,行數是隨機的。 ...這就是爲什麼我用console.in.readtoend – ikel

+0

它只給你一行 –

相關問題