Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this