Hi, i'm new to c++ (have a little VB.net) and strings are much different.
I am trying to read strings and numbers from a file, and am not having much success. specifically, i am trying to read one string and 3 different numbers into the appropriate members of a structure, and create an array of these structures, then display the array on screen.
I am able to read the first string and 3 numbers fine, but then the whole thing falls apart, and i cannot understand why.
As far as i can tell, it should work perfectly. Please help if you can. What i would like is an explanation of why my code fails, not just what changes i can make to fix it (but that'd do in a pinch).
Code:
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
ifstream fin;
int flag = 2;
int i = 0;
struct share
{
string shareName;
int noShares;
float purchasePrice;
float currentValue;
};
share portfolio[20];
while (flag > 1)
{
cout<<" MENU \n"<<"Press L to Load \n"<<"Press D to Display\n"<<"Press Q to Quit\n";
cin >> ch;
int holder = ch;
switch (holder)
{
case 76: fin.open("funds.txt");
while (i < 8)
{
getline(fin, portfolio[i].shareName,'\n');
fin>>portfolio[i].noShares;
fin>>portfolio[i].purchasePrice;
fin>>portfolio[i].currentValue;
++i;
}
flag = 3;
break;
case 68: if (flag != 3)
{
cout<<"\nNo Data Loaded\n\n";
break;
}
else if (flag ==3)
{
i = 0;
while (i<8)
{
cout<<endl<<portfolio[i].shareName<<endl;
cout<<portfolio[i].noShares<<endl<<portfolio[i].purchasePrice;
cout<<endl<<portfolio[i].currentValue<<endl;
++i;
}
}
break;
case 81: flag = 0;
break;
}
}
return 0;
}
here is the contents of the file i am trying to read (funds.txt).
Sweet Money
10
2
4
Argonauts
15
4
5
Wiggles
60
1
5
Human Gills
100
.5
333.33
Brain Implants
25
4654.4
456466.45
Clone Dawgs
66
987
789
Oil Gas Co.
100
40
61
College Football
100
34
519
thanks again.