string class and cin

Started by
3 comments, last by TheOne1 19 years, 7 months ago
how do you read characters/strings into a string object? For some reason, cin.getline() will not work with string class objects. I get this error: :\Program Files\Microsoft Visual Studio\MyProjects\tester\mainTest.cpp(17) : error C2664: 'class std::basic_istream<char,struct std::char_traits<char> > &__thiscall std::basic_istream<char,struct std::char_traits<char> >::getline(char *,int)' : can not convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char *' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
----Me: So do you know any computer languages?Friend: Ummm....yeah, I used to know l337 talk.Me: ok....
Advertisement
this should work:

getline(cin, myString);

or

std::getline(std::cin, myString);

someone else could explain exactly how that works...I know it has to do with the fact that the normal getline only accepts c-style strings, but I'm not sure why this form does
#include <iostream>#include <string>using namespace std;int main(){	string YourString = "";		getline(cin, YourString);	cout<<"Your String = "<<YourString.c_str()<<endl;	return 0;}


That works

Edit:
NewbJ beat me by 11secs :)
Quote:Original post by NewbJ
this should work:

getline(cin, myString);

or

std::getline(std::cin, myString);

someone else could explain exactly how that works...I know it has to do with the fact that the normal getline only accepts c-style strings, but I'm not sure why this form does


That works but....I have to press enter twice. Why?
----Me: So do you know any computer languages?Friend: Ummm....yeah, I used to know l337 talk.Me: ok....
ah, nm.
----Me: So do you know any computer languages?Friend: Ummm....yeah, I used to know l337 talk.Me: ok....

This topic is closed to new replies.

Advertisement