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

2

14

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();
}
Dowland answered 2/9, 2012 at 20:14 Comment(6)
You need to overload the << operator.Leeann
@Leeann - no, not here; the member function getBookInfo returns a string, and that string gets inserted.Piccard
I don't see title declared anywhere.Foment
str::string - shouldn't that be std::string?Worldlywise
@Mysticial: Its all there, I just pasted the code what causes me trouble, If I use cout in the method without cout in main method it works just fine. I just wonder why this wont work the way I am presenting. :)Dowland
@therefromhere: You are right. Sorry.Dowland
O
38

#include <string> is missing.

Oxytetracycline answered 2/9, 2012 at 20:17 Comment(1)
Problem solved... I feel stupid today lol. I didn't have it there and cout was working OK. Thanks, I'll remember for next time.Dowland
P
2

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

Piccard answered 2/9, 2012 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.