Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?
Im trying to store a whole text file as a string, how can I dynamically store any amount of characters the text file may contain?
Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?
Im trying to store a whole text file as a string, how can I dynamically store any amount of characters the text file may contain?
The C++ Standard Library provides the std::string
type for dynamically sized strings. It is a typedef for std::basic_string<char>
. There's a useful reference at cppreference.com.
For reading lines from a file into a std::string
, take a look at std::getline
. You can use it to get a line from a file as follows:
std::string str;
std::getline(file_stream, str);
Be sure to check the stream (it is returned by std::getline
) to see if everything went okay. This is often done in a loop:
while (std::getline(file_stream, str)) {
// Use str
}
In addition to sftrabbit's answer:
Note that you can read a whole file into a string in one go by doing this:
std::ifstream input_ifstr(filename.c_str());
std::string str(
(std::istreambuf_iterator<char>(input_ifstr)),
std::istreambuf_iterator<char>());
input_ifstr.close();
You can construct a stringstream from it to process with getline afterwards if you wish.