问题
So the program is working correctly, but for some reason, on the second time through, it is skipping the Console.ReadLine() prompt altogether. I ran through debug and confirmed that it isn't a loop problem as it is actually entering the method, displaying the WriteLine then completely skipping over the ReadLine, thus returning a blank back to Main() causing it to exit. What the deuce? Any ideas?
here is the code.
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();
}
}
}
回答1:
It's because of your Console.Read()
call in DisplayResults
method. It generally reads just one character. If you press ENTER (which is actually combination of 2 characters - carriage return and line feed) on Console.Read()
it only gets carriage return character, and line feed gets to your next console reading method - Console.ReadLine()
in GetInput()
method. Since line feed character is also a linux ENTER character, Console.ReadLine()
reads it as one line.
回答2:
Try changing the Console.Read()
in your DisplayResults
method to Console.ReadLine()
. That seems to make everything behave as it should.
回答3:
You said the second time round. Looking at your do-while loop, That would fall through because your variable inString is initialised and not empty.
Btw, usually safer to use
do
{
} while (!String.IsNullOrEmpty(inString));
than to directly compare to an empty string.
来源:https://stackoverflow.com/questions/3800343/c-sharp-why-is-it-skipping-my-console-readline