Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is writing a std::string to cout causing an unknown operator << error?

Tags:

c++

cout

I am getting an error when I try to output the return value from one of my methods:

Error: No operator "<<" matches these operands. Operand types are: std::ostream << std::string

Main.cpp

#include <iostream>
using namespace std;

#include "Book.h"

int main()
{
    book.setTitle("Advanced C++ Programming");
    book.setAuthorName("Linda", "Smith");
    book.setPublisher("Microsoft Press", "One Microsoft Way", "Redmond");
    book.setPrice(49.99);

    cout << book.getBookInfo(); // <-= this won't compile because of the error above.

    int i;
    cin >> i;

    return 0;
};

Method which should return string:

string Book::getBookInfo()
{
    stringstream ss;
    ss << title << endl << convertDoubleToString(price) << endl;

    return ss.str();
}
like image 393
HelpNeeder Avatar asked Sep 02 '12 20:09

HelpNeeder


People also ask

Can you cout a string in C++?

The std::cout ObjectStd::cout is the preferred way to print a string in C++.

Why is cout not working in C++?

This may happen because std::cout is writing to output buffer which is waiting to be flushed. If no flushing occurs nothing will print. So you may have to flush the buffer manually by doing the following: std::cout.

What is << In C++ cout?

The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.


2 Answers

#include <string> is missing.

like image 172
AndersK Avatar answered Sep 20 '22 05:09

AndersK


How did the code get the definition of string? The header <string> also declares the stream inserter.

like image 24
Pete Becker Avatar answered Sep 21 '22 05:09

Pete Becker