我想知道是否可以将StreamWriter输出重定向到变量
就像是
String^ myString; StreamWriter sw = gcnew StreamWriter([somehow specify myString]) sw->WriteLine("Foo");
那么myString将包含Foo.我想这样做的原因是重用一个复杂的函数.我应该将它重构为一个String返回函数,但它仍然是一个很好的黑客知道
您可以使用StringWriter将值直接写入字符串构建器对象
StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); // now, the StringWriter instance 'sw' will write to 'sb'
StreamWriter和StringWriter都扩展了TextWriter,也许你可以重构使用StreamWriter来使用TextWriter的方法,以便它可以写入流或字符串?
您应该能够使用Memory Stream完成所需的操作.
MemoryStream mem = new MemoryStream(); StreamWriter sw = new StreamWriter(mem); sw.WriteLine("Foo"); // then later you should be able to get your string. // this is in c# but I am certain you can do something of the sort in C++ String result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);
试试这段代码=]
StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string s = sb.ToString(); <-- Now it will be a string.