# Can you get getline() to work with C++ strings?

This topic is 5024 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've been trying to figure this out for a little while now, but there seems to be no mention (online at least) of a way to read strings from a text file. What I mean is that typically I see getline code with

char str[2000]

... //other defining code

for (blah = 0; blah < end_of_file; blah++)
in_stream.getline(str,2000);

... //other code, etc...


but... I usually never see example getline code that looks like this...

string example_str;

for (blah = 0; blah < end_of_file; blah++)
in_stream.getline(example_str);

//etc.


What is involved with making a getline function read to a string, instead of a character array? Why is it that my C++ compiler gives me an error message whenever I try to substitute a string for a character array pointer (which is almost essentially a string)? Thanks in advance for your assistance.

##### Share on other sites
std::getline(in_stream, example_str);

##### Share on other sites
Thanks for the assist. Tried it out though with code like this:

 example_str = std::getline(in_stream,param_string,'\n');

And I got this error:

error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class std::basic_istream<char,struct std::char_traits<char> >' (or there is no acceptable conversion)

I believe I've got a basic istream and a basic string. The '\n' is the delimiter character. What do I seem to be doing wrong here? This is literally the only error I am getting in my code. It is supposed to grab an entire line of text and put it into a string.

Could it be because I am working with a file?

Thanks for you help...
-slippers2k

##### Share on other sites
std::getline(in_stream,param_string,example_str);
std::getline already stops at the '\n' character.

##### Share on other sites
you don't need the = operator, the first paramater to get line, is the stream to get the line from, the second is the string to send it too. the third option is the delimiter if you want to specify one, but it defaults to the newline character by default.

##### Share on other sites
std::string line;
std::getline( std::cin , line );
//line == last line of text typed.

1. 1
2. 2
3. 3
Rutin
23
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633653
• Total Posts
3013166
×