3 回答

TA貢獻1860條經(jīng)驗 獲得超8個贊
Console.ReadLine()只讀取一行。 讀取第一行 當(dāng)您進入新行時。在你的情況下,只讀取第一行,然后對于第二行,你的程序只得到第一個字符并退出。string input = Console.ReadLine()
檢查這個:
int numberOfElements = Convert.ToInt32(Console.ReadLine());
int sum= 0;
for (int i=0; i< numberOfElements; i++)
{
string input = Console.ReadLine();
sum += Array.ConvertAll(input.Split(' '), int.Parse).Sum();
}
Console.WriteLine(sum);

TA貢獻1802條經(jīng)驗 獲得超10個贊
顯然,當(dāng)您粘貼回車符時,只占用到第一個回車符,您將需要一些描述的循環(huán)ReadLine
int numberOfElements = Convert.ToInt32(Console.ReadLine());
var sb = new StringBuilder();
for (int i = 0; i < numberOfElements; i++)
{
Console.WriteLine($"Enter value {i+1}");
sb.AppendLine(Console.ReadLine());
}
var input = sb.ToString();
// do what ever you want here
Console.ReadKey();

TA貢獻1828條經(jīng)驗 獲得超3個贊
我假設(shè)您正在尋找一種方法來允許用戶將其他源中的某些內(nèi)容粘貼到控制臺程序中,因此您正在尋找一個答案,您可以在其中處理來自用戶的多行字符串輸入(他們在其中粘貼包含一個或多個換行符的字符串)。
如果是這種情況,則執(zhí)行此操作的一種方法是在第一次調(diào)用后檢查 的值,以查看緩沖區(qū)中是否還有更多輸入,如果有,請將其添加到已捕獲的輸入中。Console.KeyAvailableReadLine
例如,下面是一個方法,該方法接受提示(向用戶顯示),然后返回一個,其中包含用戶粘貼(或鍵入)的每一行的條目:List<string>
private static List<string> GetMultiLineStringFromUser(string prompt)
{
Console.Write(prompt);
// Create a list and add the first line to it
List<string> results = new List<string> { Console.ReadLine() };
// KeyAvailable will return 'true' if there is more input in the buffer
// so we keep adding the lines until there are none left
while(Console.KeyAvailable)
{
results.Add(Console.ReadLine());
}
// Return the list of lines
return results;
}
在使用中,這可能看起來像這樣:
private static void Main()
{
var input = GetMultiLineStringFromUser("Paste a multi-line string and press enter: ");
Console.WriteLine("\nYou entered: ");
foreach(var line in input)
{
Console.WriteLine(line);
}
GetKeyFromUser("\nDone!\nPress any key to exit...");
}
輸出
你接下來做什么取決于你想要完成什么。如果要獲取所有行,將它們拆分為空格字符,并將所有結(jié)果作為單個整數(shù)的列表返回,則可以執(zhí)行以下操作:
private static void Main()
{
int temp = 0;
List<int> numbers =
GetMultiLineStringFromUser("Paste a multi-line string and press enter: ")
.SelectMany(i => i.Split()) // Get all the individual entries
.Where(i => int.TryParse(i, out temp)) // Where the entry is an int
.Select(i => Convert.ToInt32(i)) // And convert the entry to an int
.ToList();
Console.WriteLine("\nYou entered: ");
foreach (var number in numbers)
{
Console.WriteLine(number);
}
GetKeyFromUser("\nDone!\nPress any key to exit...");
}
輸出
或者你甚至可以做一些花哨的事情,比如:
Console.WriteLine($"\n{string.Join(" + ", numbers)} = {numbers.Sum()}");
輸出
- 3 回答
- 0 關(guān)注
- 144 瀏覽
添加回答
舉報