
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read Whole ASCII File into C++ std::string
This is a simple way to read whole ASCII file into std::string in C++ ?
Algorithm
Here is the algorithm we will follow to Read the whole ASCII file into C++ std::string.
-
Begin
Declare a file a.txt using file object f of ifstream type to perform a read operation.
Declare a variable str of string type. If(f) Declare another variable ss of ostringstream type.
Call rdbuf() function to read the data of the 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
Here is the following example of it.
#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
Advertisements