Help with reading form a file

Hi, I'm trying to build a kind of "database" of grocery products.
The idea is have a txt file with the information of the products, name, price, and maybe more stuff. At this point I'm trying to code a function that loads the information from a txt file that I previously write with an only string, I'm trying to check it by executing it in the main fuction and then showing in the console the string character that I previously read, but It doesn't work and I don't know why, so please help.

PS: thanks, and sorry for my grammar mistakes, English is not my first language.

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
 #include<iostream> 
#include<fstream> 

using namespace std;

const int MAXprod = 200;		
typedef struct{
	string name;
	double price;
}tProduct;

typedef struct{
	tProduct products[MAXprod];
	int counter;
}tList;

void loadTXT(tList);
	
int main()
{
	tList list;
	loadTXT(list);
	cout << list.products[0].name;

	return 0;
}

void loadTXT(tList myList){
	ifstream file;
	file.open("purchases.txt");
	file >> myList.products[0].name;
	file.close();
}
Last edited on
loadTXT(list);

This passes a copy of list to the function. This is called "pass by value". A copy of the variable is sent to the function.

The function then does something with that copy. When the function ends, the copy is thrown away.

This line of code:
cout << list.products[0].name;
is working with the original list variable. Your function changed (and then discarded) a copy, the original is unchanged.


As an aside, this:

1
2
3
4
typedef struct{
	tProduct products[MAXprod];
	int counter;
}tList;

is C code.

In C++, we do it like this:
1
2
3
4
struct tList{
	tProduct products[MAXprod];
	int counter;
}
Ok, thank you very much for the aid!
Topic archived. No new replies allowed.