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

3
所以程序是正常工作的,但由于某种原因,在第二次运行时,它完全跳过了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();
        }

    }
}
3个回答

11

这是因为你在DisplayResults方法中调用了Console.Read()。它通常只读取一个字符。如果你按下ENTER键(实际上是2个字符的组合——回车和换行符),那么Console.Read()仅会获取回车字符,而换行符会传递给下一个控制台读取方法——GetInput()方法中的Console.ReadLine()。由于换行符也是Linux ENTER字符,所以Console.ReadLine()将其视为一行。


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

哇,我没想到Read()也会影响ReadLine()。谢谢。 - Sinaesthetic

0

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

顺便说一句,通常更安全的做法是使用

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

与其直接与空字符串进行比较,不如采用其他方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接