How to turn a txt file into a string

I'm trying to turn a txt file into a string
so far I have got the program to write words into a txt (one per line) and am trying to get it to bring them back in as one string but am unsure of how to do this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int x;
    int y = 0;

    ofstream outputFile;
    outputFile.open ("names.txt", std::ios_base::app);
    cout << "How many names would you like to enter?\n";
    cin >> x;
    cout << "Please enter your " << x << " names\n";
    string name;

    while (y<x)
    {
        cout << y << "   ";
        cin >> name;
        outputFile << name << endl;
        y=y+1;

    }


    outputFile.close();
}


Any help appreciated thankyou.
The best I've gotten so far is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string txt;
    ifstream file("names.txt");

    if (file.is_open())
         while (file.good())
             getline(file, txt);
    file.close();

    cout << txt << endl;
    system ("pause");
    return 0;
}


but this doesnt seem to work for the way i want it done
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <fstream>
#include <iterator>
#include <sstream>

std::string stream_as_string( std::istream& stm ) // #include <iterator>
{ return { std::istreambuf_iterator<char>(stm), std::istreambuf_iterator<char>{} } ; }

std::string stream_as_string2( std::istream& stm )
{
    std::string str ;
    char c ;
    while( stm.get(c) ) str += c ;
    return str ;
}

std::string stream_as_string3( std::istream& stm ) // #include <sstream>
{
    std::ostringstream str_stm ;
    str_stm << stm.rdbuf() ;
    return str_stm.str() ;
}

int main() 
{
    std::ifstream file(__FILE__) ;
    std::cout << stream_as_string(file) << '\n' ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main () {
string s;
string sTotal;

ifstream in;
in.open("E:/Anup/Programming/C++/CPP/inf.txt");

while(!in.eof()) {
	getline(in, s);
	sTotal += s + "\n";
	
}

cout << sTotal;

in.close();	
return 0;
}
Thanks the second worked the best
Topic archived. No new replies allowed.