Jump to content
  • Advertisement
Sign in to follow this  
slippers2k

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

This topic is 4947 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
Advertisement
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
In your code you'll want:
std::getline(in_stream,param_string,example_str);
std::getline already stops at the '\n' character.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!