How to Read All Lines of Input File as String

I am working on the first part of a project for my introductory c++ course. I am writing a program where an entire file must be read by the program. The code asks the user to enter the name of a file, and then is supposed to open that file and read every line of the file as a single string. I believe that I have the file open part right (although I may be wrong), but I cannot get it to read the file correctly. (I cout the word string to see if it is there.) Any help that you can offer is appreciated. Thanks!

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
30
31
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string words;

	string openfile(){
		
	string filename;
	string inputfilename;
	ifstream inputfile;
	cout<<"Enter a file name: ";
	getline(cin, inputfilename);
	inputfile.open(inputfile(;
                while(true){
                getline(inputfile, words);
                if(words.empty()){
                break;
                }
                }
	cout<<words;
	return words;
	}
int main()
{
	openfile();
	return 0;
}
Last edited on
Well, I'm no C++ expert (yet), although I may have your solution. I had to perform a task similar to this one, and I found this page:
http://www.cplusplus.com/reference/iostream/istream/seekg/
Basically, it'll explain istream::seekg, and give you an example of loading a file to memory and outputting the data in the file. Here is an example of the program you'd write (uses practtically the exact code on the website):
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
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <fstream>
using namespace std;
void openfile()
{
    ifstream inputfile;
    string inputfilename;
    cout << "Enter a file name: ";
    getline(cin, inputfilename);
    int length;
      char * buffer;
      inputfile.open (inputfilename.c_str(), ios::binary );

      // get length of file:
      inputfile.seekg (0, ios::end);
      length = inputfile.tellg();
      inputfile.seekg (0, ios::beg);

      // allocate memory:
      buffer = new char [length];

      // read data as a block:
      inputfile.read (buffer,length);

      inputfile.close();

      cout.write (buffer,length);

      delete[] buffer;
}

int main()
{
    openfile();
    return 0;
}


I know of another approach, but this one seems fastest.
you can also do it as
1
2
3
4
ifstream ifile;
string str;
ifile.open(FILENAME);
getline(ifile,str,EOF);
Topic archived. No new replies allowed.