• Register
1 vote
18 views

Problem:

Is there any simple way to read the whole ASCII file into std::string in C++:?

Thanks

12 7 7
15,250 points

1 Answer

1 vote
 
Best answer

Solution:

Yes, it is possible. You can import a text file in a python program and read it as a string.

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

This simple code will import the file sample.txt and read it as a string.

Input

sample.txt data file containing the text “Hello World”

Output

Hello World

 

13 9 6
94,240 points

Related questions

0 votes
1 answer 8 views
8 views asked Oct 14 anonymous
1 vote
1 answer 324 views
324 views
Problem: Hello Pal, I have a query regarding the python programming language. The question is, which method will return an empty string when it has attempted to read beyond the end of a file? Do you have any idea about this? Thanks
asked Mar 16 Gavin 15.3k points
1 vote
2 answers 355 views
355 views
Problem: Hello Kodlogs, Myself is a beginner level student of c++ and I am trying to solve problems from a website. I was doing good until I got a problem that says, c++ read file line by line into vector. I was looking for a solution over the internet but I failed. Could you please solve the problem?
asked Apr 3 Gavin 15.3k points
0 votes
2 answers 5 views
5 views
Problem: I am facing this error while practicing some c++ related input-output statements. I really don't know why I am facing this error as according to me this suppose to be the syntax of the header file.
asked Oct 12 anonymous