首页 > 解决方案 > 将ostream分配给c ++中的数据类型字符串

问题描述

我有一个下面的方法,我可以通过名称理解将输出以漂亮的格式转换为显示。但我不明白这段代码在做什么,它的返回类型是什么。如何将此返回类型分配给我想从中访问的字符串数据类型javascript

std::ostream & prettyPrintRaw(std::ostream &out, const std::vector<unsigned char> &buf) {

vector<unsigned char>::const_iterator ptr = buf.begin();

vector<unsigned char>::const_iterator end = buf.end();

int i = 0;

  while (ptr != end) {

    char c = (char) *ptr; 

    if (c >= ' ' && c <= '~') {
      out.put(c);
      barCodeDataChar[i] = c;
      i++;
    }
    else
      out << '{' << (int) c << '}';

    ptr++;
  } // end while

  return out;

} // end function

抱歉,我无法对这段piece代码进行漂亮的格式化

标签: javascriptc++visual-studio

解决方案


您可以删除std::ostream &out参数,并使用字符串流来构造字符串值。

然后,您可以使用myStringStream.str()来获取字符串。

#include <sstream>
#include <string>

std::string prettyPrintRaw(const std::vector<char> &buf) {

    auto ptr = buf.begin();
    auto end = buf.end();
    std::stringstream out;

    int i = 0;

    while (ptr != end) {

        char c = (char) *ptr; 

        if (c >= ' ' && c <= '~'){
            out.put(c);
            i++;
        }
        else {
            out << '{' << (int) c << '}';
        }

        ptr++;
    }

    return out.str();
}

编辑:

显然std::vector是一个模板类,需要一个模板参数......还应该用 auto 声明迭代器(根据我的想法)。

编辑2:

该行在barCodeDataChar[i] = c;给出的代码示例中不起作用,因为barCodeDataChar未定义。


推荐阅读