functions with ifstrem

So I want to if its possible to have a function to get data from text file and store into variables instead of putting it in the main function .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  //function to read the contacts.txt file
	ifstream infile1; //Contact.txt
	infile1.open("contacts.txt");

	if (infile1.is_open())
	{
		string temp;
		float  id, cw, cs, ce, dist; //place holders 
		
		

		getline(infile1, temp);

		while (infile1 >> id >> cw >> cs >> ce >> dist)
		{
			
			user_ids[size]= id;
			contact_with[size]=cw;
			contact_start[size]=cs;
			contact_end[size]=ce;
			distance[size]=dist;
			size++;
		
Something like:
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
#include <fstream>
#include <string>
#include <vector>

struct ConfigParameter {
    ConfigParameter(const std::string& user_id, const std::string& contact) : user_id(user_id), contact(contact) {
    }
    std::string user_id;
    std::string contact;
};
using ConfigParameters = std::vector<ConfigParameter>;

ConfigParameters readConfigParameters(std::string filename) {
    ConfigParameters out;

    std::ifstream is(filename);
    while (is >> user_id >> contact)
        out.emplace_back(user_id, contact);

    return out;
}

int main(int argc, char* argv[]) {
    std::string configFile = (argc > 1) ? argv[1] : "config.txt";
    ConfigParameters config = readConfigParameters(configFile);
    for (const auto& record : config)
        std::cout << record.user_id << " : " << record.contact << "\n";
}


I haven't tried to compile this, so there'll probably be syntax errors.
Last edited on
hey thanks for replying and sorry for double posting, i thought the original one did not go through hence the double post and idk how to delete the other one 😢.
anyway as for the context on why i want to make it it own function is because it cluttering my main function as I have 2 other files I need data from so I thought it best to put it into a function , maybe make a header file and go from there .

Topic archived. No new replies allowed.