2013-03-28 38 views
2

我正在将C++代码添加到iOS应用程序,并且我想使用UITextView作为显示正在经过std :: cout的方式。我不想修改C++代码太多。如何将std :: cout重定向到UITextView?

到目前为止,我已经定义了一个名为stdcout的字符串流,在我感兴趣的C++代码捕获输出的范围内,并且在C++代码块返回后更新了UITextView。这有点侵入性,因为我需要做一些手动文本替换,而且容易出错。

有没有更好的方法来做到这一点?

+0

如果这一切都定位于一个文件,为什么不使用char *放置到输出流中,并将其放入NSString中(使用'+ stringWithUTF8String:')。然后根据需要调用'setText:' – CodaFi 2013-03-28 08:51:29

+0

我真的不想跟踪std :: cout的每个用法并修改它。 – alecail 2013-03-28 08:53:56

回答

3

你可以看看rdbuf()。

如果您关心性能/灵活性,您可以编写自定义流缓冲区并实现溢出成员,以便“自动”“实时”更新。

这里有一个简单的例子中继到一个字符串流:

#include <sstream> 
#include <iostream> 

int main() 
{ 
    std::ostringstream oss; 
    auto saved = std::cout.rdbuf(oss.rdbuf()); 

    std::cout << "hello world" << std::endl; 

    std::cout.rdbuf(saved); 
    return oss.str().length(); 
} 

这项计划与退出码“12”离开我的cygwin外壳:

./test.exe; echo $? 
12 
+0

我不熟悉流缓冲区。什么是溢出成员? – alecail 2013-03-28 09:34:34

+0

流缓冲区IME工作的最佳描述在[DietmarKühl]的答案中(http://stackoverflow.com/search?tab=votes&q=user%3a1120273%20overflow):例如, http://stackoverflow.com/questions/12716990/encrypting-and-serializing-stl-string-and-other-containers/12717492#12717492,http://stackoverflow.com/questions/13943280/c-template-operator-编译错误/ 13943353#13943353,(还[other](http://stackoverflow.com/search?tab=votes&q=user%3a1120273%20buffer)相关答案)。一定要考虑升压IOStreams。 – sehe 2013-03-28 09:49:01