cout << std::string

i wanna ask something:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

std::string get_string() {
  return std::string("My String");
}

int main () {
	std::string str1 = get_string();
	std::string& obj = str1;
	
	std::cout << str1 << std::endl;
	std::cin.get();
	return 0;
}

why this code gives an error message?

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

thx in advance...
Last edited on
Hello chipp, this program runs perfectly fine for me. It prints out "My String". Can you give us more info as what compiler you are using, what version and what standard are you using(ex. C++11)?

Thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

std::string get_string() {
  return "My String";         // will convert to std::string, std::string is optional
}

int main () {
	std::string str1 = get_string();
	std::string& obj = str1;

	std::cout << str1 << std::endl; // Prints "My String"
	std::cin.get();
	return 0;
}
My String



EDIT: ne555 has the answer :D
Last edited on
you haven't #include <string> , ┬┐why should it build correctly?
@ne555: thx
@Xp3rt: i'm using vs 2008
Alright, well I edited my first post. Overlooked that.
@ne555 depends on the compiler
Yep, mine compiled without the include thing. Which i kinda dont like
@justinelandichoruiz
Certain implementations may include <string> in other headers, however, it is not best practice to rely on that. Do you know which headers do that and in which implementations? Are you sure they include the entire header and not just parts of it?

Best practice is that if you use std::string, then you should always include <string>. Relying on implementation specific behaviour means your program probably is not portable to other implementations.
Topic archived. No new replies allowed.