• Register
1 vote
31 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,240 points

Related questions

1 vote
1 answer 754 views
754 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 14 views
14 views
Problem: A split in which commas and spaces are both delimiters, or a function that splits either on space or on comma, according to a parameter? Possible Duplicate: How to split a string? What is the right way to split a string into a vector of strings. Delimiter is space or comma.
asked Dec 23, 2020 Mashhoodch 9.6k points
0 votes
1 answer 39 views
39 views
Problem Hey, how to convert a string into a boolean value in C++
asked Dec 17, 2020 chris jordan 2.4k points
0 votes
1 answer 20 views
20 views asked Oct 14, 2020 anonymous
0 votes
2 answers 10 views
10 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 32 views
32 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 69 views
69 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 6k points
0 votes
1 answer 13 views
13 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 29 views