CW Holeman II
CW Holeman II

Reputation: 4961

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. 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.

   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%;
...

Upvotes: 2

Views: 967

Answers (1)

CW Holeman II
CW Holeman II

Reputation: 4961

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::stringstream xml_doc(APTCP_XML_DOC_PREFIX,
    std::ios::in|std::ios::out|std::ios::ate);

Upvotes: 3

Related Questions