2

noob question! How can i read 'a whole ifstream' into a stdlib 'string'? The current way i'm using for all my projects right now wastes much time i think:

string code;
ifstream input("~/myfile");
char c1=input.get();
while (c1!=EOF)
{
    code+=c1;
    len++;
    c1=input.get();
}

BTW i prefer to do line and whitespace management myself.

Hossein
  • 3,839
  • 2
  • 20
  • 43
  • 1
    See: http://stackoverflow.com/questions/3303527/how-to-pre-allocate-memory-for-a-stdstring-object/3304059#3304059 – Jerry Coffin Mar 17 '11 at 15:54

2 Answers2

7
string load_file(const string& filename)
{
    ifstream infile(filename.c_str(), ios::binary);
    istreambuf_iterator<char> begin(infile), end;
    return string(begin, end);
}
genpfault
  • 47,669
  • 9
  • 68
  • 119
  • This using iterators is more standard i think. I'll benchmark to see what way is faster though. – Hossein Mar 17 '11 at 15:35
2
#include <string>
#include <iostream>

int main() {
   std::string s;

   std::getline(std::cin, s, '\0');
   std::cout << s;
}

~

Robᵩ
  • 143,876
  • 16
  • 205
  • 276