
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What is the best way to read an entire file into a std::string in C++?
This is an simple way to read an entire file into std::string in C++
Algorithm
Begin Take the filename as inputstream. Declare a string variable str. Read the file till the end by using rdbuf(). Put the data into st. Print the data. End.
Example Code
#include<iostream> #include<fstream> #include<sstream> #include<string> using namespace std; int main() { ifstream f("a.txt"); string str; if(f) { ostringstream ss; ss << f.rdbuf(); str = ss.str(); } cout<<str; }
Input
a.txt data file contains the string “hi”
Output
hi
- Related Articles
- Read whole ASCII file into C++ std::string
- How an entire file is read into buffer and returned as a string in Python?
- What's the best way to trim std::string in C++?
- How to read a file into a string in Golang?
- How to read an entire line from a text file using Python?
- What is the best way to convert a number to a string in JavaScript?
- What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time in C#?
- What is the best way to add an event in JavaScript?
- Is there any way to embed a PDF file into an HTML5 page?
- C# Program to read contents of a file into a string at once
- What is the best way to remove an item from a Python dictionary?
- What is the easiest way to initialize a std::vector with hardcoded elements in C++?
- How to read a CSV file and store the values into an array in C#?
- What is the best way to log a Python exception?
- What is the best way to initialize a JavaScript number?

Advertisements