在 c++ 中将 ostream 分配给数据类型字符串

Assign ostream to a datatype string in c++

本文关键字:数据类型 字符串 分配 ostream c++ 中将      更新时间:2023-10-16

我有一个以下方法,我可以通过名称理解,方法是将输出转换为漂亮的格式以显示。 但是我不明白这段代码在做什么以及它的返回类型是什么。 如何将此返回类型分配给我要从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

可以删除 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 声明迭代器(根据我的 ide)。

编辑 2:

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

谢谢Kanjio,但我必须进行以下更改才能使其正常工作

std::string prettyPrintRaw1(const std::vector<unsigned char> &buf) {
vector<unsigned char>::const_iterator ptr = buf.begin();
vector<unsigned char>::const_iterator end = buf.end();
std::stringstream out;
int i = 0;
while (ptr != end) {
    char c = (char) *ptr; 
    if (c >= ' ' && c <= '~'){
        out.put(c);
    }
    else {
        out << '{' << (int) c << '}';
    }
    ptr++;
}
return out.str();

}