Read whole ASCII file into C++ std::string

C++Server Side ProgrammingProgramming

This is a simple way to read whole ASCII file into std::string in C++ −

Algorithm

Begin
   Declare a file a.txt using file object f of ifstream type to perform read operation.
   Declare a variable str of string type.
   If(f)
      Declare another variable ss of ostringstream type.
      Call rdbuf() fuction to read data of file object.
      Put the data of file object in ss.
      Put the string of ss into the str string.
   Print the value of str.
End.

Example

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main() {
   ifstream f("a.txt"); //taking file as inputstream
   string str;
   if(f) {
      ostringstream ss;
      ss << f.rdbuf(); // reading data
      str = ss.str();
   }
   cout<<str;
}

Input

a.txt data file containing the text “hi”

Output

hi
raja
Published on 28-Feb-2018 11:33:29
Advertisements