我对这样的C++代码很感兴趣:
while(getline(cin, n))
Run Code Online (Sandbox Code Playgroud)
但我想在C#中做到这一点,但我不知道如何做这样的事情。我有10行输入,它需要在一个字符串中,但Console.ReadLine()它只节省了字符串中的一行。10我的字符串变量必须有10行文本,
例如:
"first line of text\nsecond line\nthird".
Run Code Online (Sandbox Code Playgroud)
有什么办法可以像在 C++ 中那样做这样的事情吗?
如果你想模仿getline(cin, n),你可以尝试从stdin读取,即
using System.IO;
...
// Read line by line from stdin
public static IEnumerable<string> ReadStdInLines() {
using var reader = new StreamReader(Console.OpenStandardInput());
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
yield return line;
}
Run Code Online (Sandbox Code Playgroud)
例如:
using System.Linq;
...
string[] lines = ReadStdInLines()
.Take(10) // at most 10 lines
.ToArray();
Run Code Online (Sandbox Code Playgroud)