2011-03-17 2 views
2

멍청한 질문입니다! 어떻게하면 '전체 ifstream'을 stdlib '문자열'로 읽을 수 있습니까? 내가 지금 내 모든 프로젝트에 사용하고 현재의 방법은 내가 생각하는 많은 시간을 낭비 : ifstream을 문자열로 읽는 가장 효율적인 방법은 무엇입니까?

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

이 BTW 내가 라인과 공백 관리 나 자신을 선호합니다.

+1

참조 : http://stackoverflow.com/questions/3303527/how-to-pre-allocate-memory-for-a-stdstring-object/3304059#3304059 –

답변

8
string load_file(const string& filename) 
{ 
    ifstream infile(filename.c_str(), ios::binary); 
    istreambuf_iterator<char> begin(infile), end; 
    return string(begin, end); 
} 
+0

이 반복기를 사용하여 더 많은 표준을 생각합니다. 나는 벤치마킹을 통해 어떤 방법이 더 빠를지를 보게 될 것이다. – Hossein

2
#include <string> 
#include <iostream> 

int main() { 
    std::string s; 

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

~

관련 문제