【问题标题】:Assign ostream to a datatype string in c++将ostream分配给c ++中的数据类型字符串
【发布时间】:2019-05-28 07:43:47
【问题描述】:

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

【问题讨论】:

标签: javascript c++ visual-studio


【解决方案1】:

您可以删除std::ostream &amp;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 未定义。

【讨论】:

    【解决方案2】:

    感谢 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();
    

    }

    【讨论】:

    • 还有拼写 Kanjiu 而不是 Kanjio ;)
    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多