0

I have a text file like this:

1 2 3
4
5 6 7 8
just with money we can live
2 5

with this piece of code, I can show whole it on screen, but I cannot put it in a string, and its compile gives error :

string test ="";
string line2;

freopen("a.txt", "rb", stdin);
   while(getline(cin, line2)) {
       cout << line2 << endl;
       line2 >> test;
} 

1- Is it possible to put whole of text file in "test"?
2- and instead of using something like this :

string test =
"1 2 3"
"4"
"5 6 7 8"
"just with money we can live"
"2 5";

is it possible to use a loop and freopen or something like these?

I read this "Read file line by line using ifstream in C++", but it is for identical number of column.

If there is a website to answer my question, please give it to me.

  • Do you want to write `test = line2;`? – Tobias Wollgam Nov 09 '19 at 22:10
  • Possible duplicate of [What is the best way to read an entire file into a std::string in C++?](https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c) – walnut Nov 09 '19 at 22:12
  • Part 1 of your question is a dupe of [the question suggested by uneven_mark](https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c); and part 2 is difficult to understand. Are you asking about string literals with multiple lines? – einpoklum Nov 09 '19 at 22:18
  • thanks all members and their useful answers , @Paul92 works for me –  Nov 09 '19 at 22:20

2 Answers2

0

Let's have a look at this snippet:

string test ="";
string line2;

freopen("a.txt", "rb", stdin);
while(getline(cin, line2)) {
       cout << line2 << endl;
}

What happens here is that you redirect the text file (not totally accurate terminology) to the standard input stream (represented by the cin object here), and you read it line by line. Then, after reading each line, you print it to the standard output stream using the cout object.

What you need to do to read the file into a string is something along the lines:

string test ="";
string line2;

freopen("a.txt", "rb", stdin);
while(getline(cin, line2)) {
       test += line2 + "\n";
}

Here, you simply add lines to test. Note that you need to add the newlines too, since getline removes them.

Paul92
  • 8,109
  • 1
  • 17
  • 33
0

Putting the content of a file into an std::string is trivial:

std::string test{std::istreambuf_iterator<char>{std::ifstream{"a.txt"}.rdbuf()},
                 std::istreambuf_iterator<char>{}};
Dietmar Kühl
  • 141,209
  • 12
  • 196
  • 356