Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing string to ostream

Tags:

c++

gcc

When I try to compile the code below (in a Qt 4.8 using llvm-g++-4.2 (GCC) 4.2.1), I get the following error:

../GLWidget.cpp:24:   instantiated from here
../GLWidget.cpp:24: error: explicit instantiation of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]' but no definition available 

What does this error mean, and what should I do to fix it?

Source code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void testOStream(){
    filebuf fb;
    fb.open ("test.txt",ios::out);
    std::ostream os(&fb);
    std::string test("test");
    os << test; // This line has the problem
    fb.close();
}
like image 616
Mortennobel Avatar asked Oct 21 '22 21:10

Mortennobel


1 Answers

If you are using a C++ version prior C++11, you may want to add #include <ostream> to your program.

Only with C++11 and later <iostream> is required to #include <ostream>.

Header <iostream> synopsis

C++2003:

namespace std {
   extern istream cin;
   extern ostream cout;
   extern ostream cerr;
   extern ostream clog;

   extern wistream wcin;
   extern wostream wcout;
   extern wostream wcerr;
   extern wostream wclog;

}

C++2011:

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
    extern istream cin;
    extern ostream cout;
    extern ostream cerr;
    extern ostream clog;

    extern wistream wcin;
    extern wostream wcout;
    extern wostream wcerr;
    extern wostream wclog;
}
like image 181
Sebastian Mach Avatar answered Oct 28 '22 23:10

Sebastian Mach