-
1 Attachment(s)
Need help with
Hello,
As I'm trying to make a project that saves costs by user input into a CSV. File, I'm facing a problem that I can't resolve. In the first lines of the code I'm creating the part where I ask for the user input and store it in a CSV file. The problem is whenever I run the program again, it adds the new user input beside each other and not in the next cell below it. As you can see in the screenshot it says 1710 but 17 was the first input with the first run and 10 was the second input with the second run. I don't want this beside each other, but with each run a new cell under the previous input.
If you have any improvements, please share with me as i'm still learning.
If someone can help me with this. :)
Code:
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int cost;
int main(){
cout << "Hello, this is a tracker! \n" << endl;
cout << "Start by choosing your activity: \n" << endl;
cout << "1. Add costs: \n" << endl;
cout << "2. Show the content of the file: \n" << endl;
cout << "3. Exit \n " << endl;
int choice;
cin >> choice;
if ( choice == 1) {
cout << "Please give me your costs: \n" << endl;
cin >> cost;
cout << "Your cost will be added to your file! \n" << endl;
ofstream costfile;
costfile.open ("costfiles.csv", ios::app);
costfile << cost;
costfile.close();
}
if ( choice == 2) {
cout << "Ill give you the content, hold on! \n" << endl;
ifstream openfile;
openfile.open("costfiles.csv", ios::app);
while (openfile >> cost) { // This cost is for storing each value in the file
cout << cost << endl; // Displaying the values that has been saved in the variable 'cost'.
}
}
return 0;
}
Attachment 36063
-
Re: Need help with
> I don't want this beside each other, but with each run a new cell under the previous input.
So output a newline then with each record.
Code:
ofstream costfile;
costfile.open ("costfiles.csv", ios::app);
costfile << cost << '\n';
costfile.close();
-
Re: Need help with
[When posting code, please use code tags so that the code is readable!]
-
Re: Need help with
Perhaps something like this:
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
cout << "Hello, this is a tracker!\n";
for (int choice {}; choice != 3; ) {
cout << "\n1. Add costs:\n";
cout << "2. Show the content of the file:\n";
cout << "3. Exit \n";
cout << "\nPlease choose your activity: ";
switch (cin >> choice; choice) {
case 1:
{
int cost {};
cout << "Please give me your cost: ";
cin >> cost;
cout << "Your cost will be added to your file! \n";
if (ofstream costfile { "costfiles.csv", ios::app })
costfile << cost << '\n';
else
cout << "Cannot open output file\n";
}
break;
case 2:
cout << "I'll give you the content, hold on! \n";
if (ifstream openfile { "costfiles.csv" })
for (int cost {}; openfile >> cost; cout << cost << '\n');
else
cout << "Cannot open input file\n";
break;
case 3:
break;
default:
cout << "Invalid option\n";
break;
}
}
}