May 30, 2008 at 2:26am UTC
im writing a program that uses data from a .txt file. i have been working on this code for quite awhile now and cant quite get it. i want the file to extract information from "funds.txt" which looks like this:
Harry & David Inc
50
12.99
19.85
i want the program to load the information from the file by typing "L" then display the information by typing "D"
so far this is what i got:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
char answer;
fstream data;
string fundName = "";
int numberOfShares = 0;
double purchasePrice = 0, currentValue = 0;
cout << fixed << showpoint;
cout << left;
cout << setw(5) << " " << "Menu" << endl;
cout << setw(5) << "L" << "load from file" << endl;
cout << setw(5) << "D" << "display" << endl;
cout << setw(5) << "Q" << "quit" << endl;
cin >> answer;
while (answer != 'Q')
{
if (answer == 'L')
{
data.open("funds.txt",ios::in);
getline(cin, fundName);
data >> fundName; >> numberOfShares >> purchasePrice
>> currentValue;
}
else if (answer == 'D')
{
cout << fundName; << numberOfShares << purchasePrice
<< currentValue;
data.close();
}
cin.clear();
cin.ignore(200,'\n');
cout << setw(5) << " " << "Menu" << endl;
cout << setw(5) << "L" << "load from file" << endl;
cout << setw(5) << "D" << "display" << endl;
cout << setw(5) << "Q" << "quit" << endl;
}
system("pause");
return 0;
}
can someone please help me?
May 30, 2008 at 3:27am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
while (answer != 'Q' )
{
if (answer == 'L' )
{
data.open("funds.txt" ,ios::in);
getline(cin, fundName);
data >> fundName; >> numberOfShares >> purchasePrice
>> currentValue;
}
else if (answer == 'D' )
{
cout << fundName; << numberOfShares << purchasePrice
<< currentValue;
data.close();
}
on loading I think you must check if its end of file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
int main () {
string line;
ifstream myfile ("funds.txt" );
if (myfile.is_open())
{
/* while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}*/
getline(myfilen fundName);
getline(myfile, numberOfShares);
getline(myfile, purchasePrice);
getline(myfile, currentValue);
myfile.close();
}
else cout << "Unable to open file" ;
return 0;
}
unless its just a single line...
I think something is wrong about your
1 2 3 4 5 6 7 8 9 10 11 12
ifstream myfile ("funds.txt" );
if (myfile.is_open()) {
myfile << fundName;
myfile << numberOfShares ;
myfile << purchasePrice ;
myfile << currentValue;
myfile.close();
}
else cout << "Unable to open file" ;
return 0;
and i think data.open() and data.close() should be visible at the same code block
Last edited on May 30, 2008 at 4:05am UTC