PDA

Click to See Complete Forum and Search --> : Vector string extraction using cout?


nemaroller
Dec 10th, 2001, 07:44 PM
I simply want to extract some values from a string vector, but the following code gives me errors
#include<iostream.h>
#include<vector>
#include<string>
using namespace std;

void main(){
vector<string> r;
r.push_back("Hi");
r.push_back("There");
cout << r[0] << endl;
cout << r[1] << endl;
}

errors:
C:\Windows\vectorsample.cpp(10) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion
)
C:\Windows\vectorsample.cpp(11) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion
)

So I'm guessing that the << operand wont automatically extract a string vector(although it works with int,char,etc)....

How do I do this? Do I need to overload the << operator, and if so, could someone explain to me how to do this, in code, or otherwise.

Thank you...

Zaei
Dec 10th, 2001, 08:04 PM
cout << r[0] << endl;
cout << r[1] << endl;

should be

cout << r[0].c_str() << endl;
cout << r[1].c_str() << endl;


If im not mistaken. That function returns a regular char*, that cout can work with.

Z.

nemaroller
Dec 10th, 2001, 08:22 PM
Thanks, that worked..

kedaman
Dec 10th, 2001, 08:23 PM
*** don't they overload iostream operators?

Zaei
Dec 10th, 2001, 09:05 PM
Laziness =).

Z.

kedaman
Dec 10th, 2001, 09:25 PM
bastards thats like one line of code

parksie
Dec 11th, 2001, 02:13 PM
Aah...but they did ;)

Check out istream_iterator and ostream_iterator. You can use those with copy to do things like this.

nemaroller
Dec 11th, 2001, 10:31 PM
so how would i use that in the above code?

parksie
Dec 13th, 2001, 06:54 AM
I just noticed the real problem.

Use <iostream>, not <iostream.h>.

The old one doesn't support strings.

nemaroller
Dec 13th, 2001, 08:32 AM
You see, its crap like that which makes me doubt why this happens in C++ more than any language.

Why didn't they just change the fricken name....

But IT DID WORK NOW, albeit with 4 warnings about it, but not errors!

parksie
Dec 13th, 2001, 10:42 AM
It happens in C++ because it's a relatively new language. The standard was only frozen a couple of years ago, and many compilers still aren't up to speed on the newest feature, which is template-based streams. These are the new standard, and are under <iostream>. The old <iostream.h> shouldn't be used any more.

PS: It doesn't do anything for you because it assumes you know what you're doing ;) Don't expect C++ (or its parent C) to coddle you - it will let you trash the system.