从ostringstream获取最长行数的巧妙方法

时间:2017-08-14 10:26:50

标签: c++ stl

我想做那样的事情:

std::ostringstream os;
writingSomeDataToStream(os);
const size_t width = getNumberOfCharsInLongestLine(os);
const auto header = generateHeader("My diagnostic data", width);
showText(header);
showText(os.str());

如何尽可能快地编写函数getNumberOfCharsInLongestLine?

1 个答案:

答案 0 :(得分:0)

我的决议是:

size_t getNumberOfCharsInLongestLine(const std::string& str)
{
    size_t longest = 0;
    size_t counter = 0;
    for (auto c : str)
    {
        if (c == '\n')
        {
            if (counter > longest)
                longest = counter;
            counter = 0;
        }
        else
          ++counter;
    }
    return longest;
}