Get line from txt file into string (every line if wished)

Howdy strangers,

I want to get the content of a .txt file into strings. I already got this:

1
2
3
4
5
6
7
8
9
10
                string content;
                ifstream datafile ("ConsoleTest/data.txt");
                if(datafile.is_open()) {
                    while(getline(datafile, content)) {
                        string line0;
                        string line1;

                    }
                }
                datafile.close();


But how do I get every single line (yet, there are just two lines, so 0 is 1 and 1 is 2)?

I hope, that you understand, what I mean.

Greetings,
Ben
Hello minimalistisch,

Welcome to the forum,

What you wan to do is something like 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
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <limits>
#include <fstream>
#include <vector>

int main()
{
	std::vector vec;
	std::string content;

	ifstream datafile("ConsoleTest/data.txt");

	if (!datafile.is_open())  // <--- Changed.
	{
		//std::cout<<... Error mesage of your choice.
		std::this_thread::sleep_for(std::chrono::seconds(3));  // Requires header files "chrono" and "thread"
		exit(1);  // <--- No reason to continue.
	}

	while (getline(datafile, content))  // <--- Will read the entire file.
	{
		// <--- Best to put content into a vector or array.

		vec.emplace_back(content);

		// Not really needed.
		//string line0;
		//string line1;

	}

	datafile.close();

        // Used to keep the console window open before the return ends 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;
}


This should work unless I really missed something, but i do not think so. The vector information is giving me a problem at the moment. I think I need to shut everything down and restart my computer. The I will try again.

Hope that gives you some ideas and helps,

Andy
Topic archived. No new replies allowed.