Tabrez Ahmed
Tabrez Ahmed

Reputation: 2960

Printing out std::string

In the sample code below

    std::string result = exec( "dir" ) ;
    cout<<result;

I get the following error

error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string

I suspect there is a special method to print out an std::string.

Please help me debug this.

Also, I have included iostream.h, fstream.h and stream header files.

Upvotes: 2

Views: 8281

Answers (4)

Ozzy
Ozzy

Reputation: 64

cout is defined in <iostream>. Getting the << syntax to work with std::strings requires <sstream>.

#include <iostream>
#include <sstream>

std::string result = "something";
std::cout << result << " and something else";

Upvotes: 2

Tabrez Ahmed
Tabrez Ahmed

Reputation: 2960

Answering my own question on behalf of @MrLister since he was inactive.

I should have included <iostream> and <fstream> without .h. Also using namespace std; should have been typed after that.

Ex:

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

using namespace std;

Many many thanks to @MrLister.

And thanks to @dasblinkenlight. His answer enhanced a little bit.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

I suspect that you need to qualify cout with std::

    std::cout << result;

or add using namespace::std to the top of your cpp file.

Upvotes: 3

Hakan Serce
Hakan Serce

Reputation: 11266

You need to include <string>

Upvotes: 2

Related Questions