0

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?

3

2 Answers 2

9

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 } 
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.