• Register
1 vote
55 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

Please log in or register to answer this question.

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,260 points

Related questions

1 vote
1 answer 998 views
998 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, 2020 Gavin 15.3k points
0 votes
1 answer 40 views
40 views
Problem: I have very little knowledge of C++ as I have not worked a lot in C++. I can across the above-mentioned question. There were two options cin&raquo; getline() I am not sure what the correct answer is but I chose cin&raquo;. Please tell me the correct answer and justify it too. Thanks!
asked Mar 3 Code Learner 9.8k points
0 votes
1 answer 10 views
10 views
Problem: I really don't know why I am facing this error: iostream h no such file or directory .
asked Mar 19 Wafa Abu Yousef 6.1k points
0 votes
1 answer 15 views
15 views
Problem: HOW to solve this, any help: iostream h no such file or directory
asked Mar 17 Wafa Abu Yousef 6.1k points
0 votes
2 answers 21 views
21 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, 2020 anonymous
0 votes
1 answer 63 views
63 views
Problem Hey, what is the difference between null and null pointer. Answer me with the help of an example.
asked Dec 17, 2020 chris jordan 2.4k points
0 votes
1 answer 138 views
138 views
Problem: Hello! My question is that what is endl and what is the difference between endl and \n in c++?
asked Oct 14, 2020 Code Learner 9.8k points
0 votes
1 answer 24 views
24 views
Problem: Hello everyone, I am new to the programming I just want to know why we use header files and we are using iostream header in every other code file.What it has to do with my code. Thanks
asked Oct 12, 2020 SapperIt 1.2k points
0 votes
1 answer 39 views