简体   繁体   English

C ++ std :: stringstream运算符<< vs(构造函数)

[英]C++ std::stringstream operator<< vs (constructor)

My expectation is that I can create an uninitialized std::stringstream and feed it a string or just create it with the same stream initially and get the same results. 我的期望是,我可以创建一个未初始化的std::stringstream并为它提供一个字符串,或者只是最初使用相同的流创建它并获得相同的结果。 When I did the first case the code was working as I expected. 当我做第一种情况时,代码按预期工作。 Then I tried the second case expecting there would be the same result which did not happen. 然后,我尝试了第二种情况,期望会有相同的结果,但不会发生。 What am I missing? 我想念什么?

Fragment of the first case. 第一种情况的片段。

...
int main() {
constexpr auto APTCP_XML_DOC_PREFIX            {R"EOD(<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE doc [<!ENTITY nbsp "&#xa0;">]>
<doc>
<head>
</head>
<body>
)EOD"};
   std::stringstream xml_doc; xml_doc << APTCP_XML_DOC_PREFIX;
...
   if (transformer.transform(xml_doc, style_sheet, std::cout) != 0)
      std::cerr << "aptcp/main()/transformer.getLastError(): " << transformer.getLastError() << "\n" << style_sheet.str() << xml_doc.str();
   }

Second case has xml_doc initialized this way instead. 第二种情况是xml_doc这种方式初始化了xml_doc

   std::stringstream xml_doc(APTCP_XML_DOC_PREFIX);

with this error: 出现此错误:

Fatal Error: comment or processing instruction expected (Occurred in an unknown entity, at line 2, column 1.)
aptcp/main()/transformer.getLastError(): SAXParseException: comment or processing instruction expected (Occurred in an unknown entity, at line 2, column 1.)
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet id="aptcp_stylesheet"
                version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output
            method="html"
            version="4.01"
            indent="yes"
            doctype-system="http://www.w3.org/TR/html4/strict.dtd"
            doctype-public="-//W3C//DTD HTML 4.01//EN"/>
<xsl:template match="xsl:stylesheet" />
<xsl:param name="current_time_p"/>
<xsl:template match="/">
  <html>
  <body>
    <style>
    pp {display: none;}
    pp, table, tr {
        width: 100%;
...

This code: 这段代码:

#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <cstring>

int main() {
    constexpr auto BEFORE {"Before"};

    std::stringstream un; un << BEFORE;
    un << "UN";
    std::cout << "un=" << un.str() << "." << std::endl;

    std::stringstream con(BEFORE);
    con << "CON";
    std::cout << "con=" << con.str() << "." << std::endl;
    }

shows the value is placed at the front rather than at the end. 显示该值放在前面而不是结尾。

un=BeforeUN.
con=CONore.

To answer the question, the mode is missing ( std::ios::ate "seek to the end of stream immediately after open" ): 要回答这个问题,缺少模式( std::ios::ate “打开后立即搜索到流的末尾” ):

std::stringstream xml_doc(APTCP_XML_DOC_PREFIX,
    std::ios::in|std::ios::out|std::ios::ate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM