How do I read an entire file into a std::string in C++?

后端 未结 15 2327
余生分开走
余生分开走 2020-11-21 23:51

How do I read a file into a std::string, i.e., read the whole file at once?

Text or binary mode should be specified by the caller. The solution should b

15条回答
  •  庸人自扰
    2020-11-22 00:10

    Use

    #include 
    #include 
    #include 
    
    int main()
    {
      std::ifstream input("file.txt");
      std::stringstream sstr;
    
      while(input >> sstr.rdbuf());
    
      std::cout << sstr.str() << std::endl;
    }
    

    or something very close. I don't have a stdlib reference open to double-check myself.

    Yes, I understand I didn't write the slurp function as asked.

提交回复
热议问题