逐行循环遍历char数组的最佳方式

Best way to loop through a char array line by line

本文关键字:最佳 方式 数组 char 循环 遍历 逐行      更新时间:2023-10-16

我有一个char数组,其中包含从web检索到的文本文件。逐行循环并显示每个缓冲区的最佳方式是什么线

好吧,因为这是c++,所以将您的char数组转换为字符串流,然后像处理任何其他流/文件一样处理它。当然,这样做可以调用getline()之类的函数。

string tmpstr(chararry,length); // length optional, but needed if there may be zero's in your data
istringstream is(tmpstr);
string line;
while (getline(is,line)) {
    // process line
}

另一个答案是一个很好的解决方案,但将char数组复制到临时字符串中会产生成本。这可以通过使用Boost的iostream来避免——这可以避免复制缓冲区,同时让您将其视为任何其他流。

#include <boost/iostreams/stream.hpp>
boost::iostreams::stream<boost::iostreams::array_source> stream(buffer, size);