Loading a file into a vector

前端 未结 5 497
后悔当初
后悔当初 2020-12-03 03:20

I would like to load the contents of a text file into a vector (or into any char input iterator, if that is possible). Currently my code looks like

5条回答
  •  难免孤独
    2020-12-03 03:49

    Another approach, using rdbuf() to read the whole file to a std::stringstream first:

    #include 
    #include 
    #include 
    #include 
    
    // for check:
    #include 
    #include 
    #include 
    
    int main() {
       std::ifstream file("test.cc");
       std::ostringstream ss;
       ss << file.rdbuf();
       const std::string& s = ss.str();
       std::vector vec(s.begin(), s.end());
    
       // check:
       std::copy(vec.begin(), vec.end(), std::ostream_iterator(std::cout));
    }
    

提交回复
热议问题