I’d like to read whole content of a text file to a std::string object with c++.
With Python, I can write:
text = open('text.txt', 'rt').read()
It is very simple and elegant. I hate ugly stuff, so I’d like to know – what is the most elegant way to read a text file with C++? Thanks.
There are many ways, you pick which is the most elegant for you.
Reading into char*:
Into std::string:
Into vector<char>:
Into string, using stringstream:
file.txt is just an example, everything works fine for binary files as well, just make sure you use ios::binary in ifstream constructor.