Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi i am a beginner and am a little puzzled on how to make work of the fstream.My assignment says that i need to "use 1 read/write operation".I wanted to know if the information i have obtain throught the user from my code can be saved in a .txt file?And if yes using istream or ostream?

What I have tried:

This is my code,the class that i use to get the product,and later on wanting to save the print product in my list.txt i have.This is all i understand for now thank you for any help.

C++
class Class
{
public:
	int n , amount; string name; float weight;
	vector <string> names;
	vector <int> amounts;
	vector <float> weights;
	void getproducts()
	{
		for (int i = 0; i < n; i++)
		{
			cout << "Give product "<<i+1<<" name,amount and weight : " << endl;
			cin >> name >> amount >> weight;//getting temporary variables.
			names.push_back(name);//assigning them.
			amounts.push_back(amount);
			weights.push_back(weight);
		}
	}
	void printproducts()
	{
		int totali = 0;
		cout << "\nProduct display:\n";
		cout	<< endl;
		for (int i = 0; i < n; i++)
		{
			cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
			cout << "------------------------" << endl;
			totali = amounts[i] * weights[i] + totali;
		}
		cout << "Total: ";
		cout << totali << " $ " << endl;
	}
};

int main()
{
	Class market;
	market.getproducts(); market.printproducts();
	ifstream inFile;
	inFile.open("list.txt");
	if (!inFile.fail())
	{
		cout << "Error in opening file." << endl;
		exit(1);
	}



	cin.get(); cin.get();
	return 0;
}
Posted
Updated 31-May-20 13:44pm

1 solution

You asked about fstream specifically, so I'll stick to that. I haven't looked at the rest of your code in any detail, because something caught my eye straight away.

In main(), you write
if (!inFile.fail())
{
   cout << "Error in opening file." << endl;
   exit(1);
}

If everything has gone well to this point, this will always print the error message and exit! The reason is that you've conflated two things:

if(!infile)
checks for an error, and so does
if(infile.fail())
but
if(!infile.fail())
means "If there isn't an error, then...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900