File reading problem

How can I .txt file ( foo.txt) load and store in string variable as it is in file?

I need to load foo.txt and store it in string example

have in foo.txt

I am learning file reading


and need to get

string example = "I am learning file reading"
Last edited on
http://www.cplusplus.com/forum/beginner/268165/#msg1153959

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

// https://stackoverflow.com/questions/116038/how-do-i-read-an-entire-file-into-a-stdstring-in-c
std::string slurp(std::ifstream& in) {
    std::stringstream sstr;
    sstr << in.rdbuf();
    return sstr.str();
}

int main()
{
	std::ifstream fin("main.cpp"); // (this file)
	std::string contents = slurp(fin);
	std::cout << contents << '\n';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() { 

	fstream myfile;
	string example;

	myfile.open("somefile.txt");
	getline(myfile, example);

	cout << example;

	myfile.close();
	return 0;
}
Yeah now that I re-read the OP, that is a lot simpler... :)
Thanks a lot!
Hello pajaPatak,

Although Manga has a nice simple program I see one flaw. On line 9 "myfile" is defined as a "fstream", but on line 12 it does not say if the stream is for input or output. Using an "fstream" this way you need to tell the "open" statement if it is for "input" or "output".

Ganado's example dealt with this by using "ifstream". The opposite is "ofstream" for output.

These may be of some help:
http://www.cplusplus.com/reference/fstream/fstream/fstream/
http://www.cplusplus.com/reference/fstream/fstream/open/

Back when I first started working with files I came up with this. Over time it has been revised slightly:
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
39
40
41
42
43
44
// <--- Most often used includes.
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
//#include <chrono>
//#include <thread>

#include <fstream>

int main()
{
	const std::string inFileName{ "Test.txt" };

	std::string testString;

	std::ifstream inFile(inFileName);

	if (!inFile)
	{
		std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
		//std::cout << "\n File \"" << inFileName << "\" did not open" << std::endl; // <--- A different option. Does the same as above.

		//std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread". Optional as is the header files.

		return 1; // <--- No point to continue until you fix the problem. Any number greater than (0) zero denotes a problem.
	}

	while (std::getline(inFile, testString))
	{
		std::cout << "\n The file read is: " << testString << '\n';
	}


	inFile.close();

	// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
	//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;  // <--- Not required, but makes a good break point.
}

Lines 6, 7 and 23 you may not be ready for yet. I would suggest leaving them as comments for future use some day.

This is a good time to point out the use of a good variable name and blank lines to break up the program. The variable names are still your choice, but learning to use a good variable name, a noun and sometimes a verb that describes what it does or is used for, helps to make the code easier to read. The easier it is to read the better for you and the easier it is for others when you have a question.

The blank lines break up the code making it easier to read and flow.

Line 16 defines the stream and opens the file at the same time. An easy to eliminate the need for the ".open()".

Lines 18 - 26 are the most important part here. Line 16 may open the file, but how do you know it is open? You do not. You could attempt to open the stream and it could fail, but still continue with the program and not be able to read anything.

When opening a file stream for input is is more a must to check that it opened correctly.

This is not as necessary for an output file as if the file does not exist it will first be created before it is written to. Should you use a path to the file then it is important to check that it opened because the path could be wrong or have something misspelled in it.

Lines 28 - 31 is the most common way to read a file of unknown length. This way when something happens to the file stream, say you tried to read past "end of file", the while condition would fail and the loop would continue with whatever follows.

Closing the file is more optional these days because when "main" ends and looses scope the stream will close. Personally I think it is just good form to close the stream when you are done, but that part is up to you.

Lines 36 to 42 are up to you if you want to keep or use them.

This is one suggestion and someone may even tell me a better way I could do this, but for now you may find it useful when getting started.

One last point/suggestion when your programs use variables like "bool", "char", "int" and "double" you should initialize these variable when defines if for no other reason than to know that they do not contain a "garbage" value.

Andy
Topic archived. No new replies allowed.