Jump to content
  • Advertisement
Sign in to follow this  
linternet

Stupid STL Question

This topic is 4091 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'm trying to read an entire file into a string using ifstream but the ifstream.read seems to need a char*. How do I read the data into a string without using a char* and initializing the string with it? Or is there another STL class that works better?

Share this post


Link to post
Share on other sites
Advertisement
std::vector<char>, which is guaranteed to be contiguous. Resize it to an adapted size, and then pass the address of its first element to the reading function.

Share this post


Link to post
Share on other sites
Quote:
Original post by linternet
I'm trying to read an entire file into a string using ifstream but the ifstream.read seems to need a char*.


#include <algorithm>
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

using namespace std;

const string filename("sb.cpp");

int main()
{
ifstream istr(filename.c_str());
if (!istr)
{
cerr << "error " << errno << " opening " << filename << ": "
<< strerror(errno) << "\n";
exit(1);
}

string image = string(istreambuf_iterator<char>(istr),
istreambuf_iterator<char>());

cout << "image length is " << image.length() << "\n";
cout << "-- begin image dump --\n";
cout << image << "\n";
cout << "-- end image dump --\n";
}


Share this post


Link to post
Share on other sites
Thank you both.

This:

string image = string(istreambuf_iterator&lt;char&gt;(istr),
istreambuf_iterator&lt;char&gt;());



is very cool :)

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!