C#为什么跳过我的console.readline()?

所以程序运行正常,但由于某种原因,在第二次通过时,它完全跳过Console.ReadLine()提示。 我经历了调试并确认它不是循环问题,因为它实际上正在进入方法,显示WriteLine然后完全跳过ReadLine,从而返回一个空白回Main()导致它退出。 什么是平分? 有任何想法吗?

这是代码。

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB4B { class Program { static void Main(string[] args) { string inString; ArrayList translatedPhrase = new ArrayList(); DisplayInfo(); GetInput(out inString); do { GetTranslation(inString, translatedPhrase); DisplayResults(inString, translatedPhrase); GetInput(out inString); } while (inString != ""); } static void DisplayInfo() { Console.WriteLine("*** You will be prompted to enter a string of ***"); Console.WriteLine("*** words. The string will be converted into ***"); Console.WriteLine("*** Pig Latin and the results displayed. ***"); Console.WriteLine("*** Enter as many strings as you would like. ***"); } static void GetInput(out string words) { Console.Write("\n\nEnter a group of words or ENTER to quit: "); words = Console.ReadLine(); } static void GetTranslation(string originalPhrase, ArrayList translatedPhrase) { int wordLength; string[] splitPhrase = originalPhrase.Split(); foreach (string word in splitPhrase) { wordLength = word.Length; translatedPhrase.Add(word.Substring(1, wordLength - 1) + word.Substring(0, 1) + "ay"); } } static void DisplayResults(string originalString, ArrayList translatedString) { Console.WriteLine("\n\nOriginal words: {0}", originalString); Console.Write("New Words: "); foreach (string word in translatedString) { Console.Write("{0} ", word); } Console.Read(); } } } 

这是因为您在DisplayResults方法中调用了Console.Read() 。 它通常只读取一个字符。 如果在Console.Read() )上按ENTER键(实际上是2个字符的组合 – 回车和换行符),它只会获得回车符,并且换行符会到达下一个控制台读取方法 – GetInput() Console.ReadLine() GetInput()方法。 由于换行符也是linux ENTER字符,因此Console.ReadLine()将其作为一行读取。

尝试将DisplayResults方法中的Console.ReadLine()更改为Console.ReadLine() 。 这似乎使一切都表现得如此。

你第二次说了。 看看你的do-while循环,那将会失败,因为你的变量inString是初始化的而不是空的。

顺便说一句,通常使用起来更安全

 do { } while (!String.IsNullOrEmpty(inString)); 

而不是直接比较空字符串。