Elchanan
Elchanan

Reputation: 25

read data from file into multiple arrays in c++

I have a function that is supposed to read data from a file to three arrays. Each line to another array. The first two are of type string and the third is of type double. For some reason which I can't seem to figure out, when the line to read the double is not commented out, only the first three lines display properly.

const int SYMB_LEN = 25;
const int NAME_LEN = 25;
void read_stocks(char[][SYMB_LEN], char[][NAME_LEN], double[]);

int main() {
    char symble[10][SYMB_LEN];
    char name[10][NAME_LEN];
    double price[10];
    read_stocks(symble, name, price);
    system("pause");
    return 0;
}

void read_stocks(char symble[][SYMB_LEN], char name[][NAME_LEN], double price[]) {
    ifstream fin;
    fin.open("c://cplusplus//stocks.dat");

    if (!fin) {
        cout << "Data file not found.";
        exit(1);
    }
    price[0] = 0;
    unsigned int temp = 0;
    while (!fin.eof() && temp < 10) {
        fin.getline(symble[temp], SYMB_LEN);
        fin.getline(name[temp], NAME_LEN);
        fin >> price[temp];
        cout << symble[temp] << endl;
        cout << name[temp] << endl;
        cout << price[temp] << endl;
        //cout << temp << endl;
        temp++;
    }
    fin.close();
}

This is what's in the file I'm reading:

AAPL
Apple Computer
27
LU
Lucent Technologies
72
NSCP
Netscape
27.75
MOT
Motorola
49.5
PLAT
Platinum Technologies
24.125
SEEK
Infoseek
32.5
YHOO
Yahoo
126
T
AT&T
63
PSFT
Peoplesoft
42.25
PPOD
Peapod
4.5

Upvotes: 1

Views: 800

Answers (1)

dimm
dimm

Reputation: 1798

After reading the double, you need to read the newline after the number.

fin.getline(symble[temp], SYMB_LEN);
fin.getline(name[temp], NAME_LEN);
fin >> price[temp];
fin.ignore(numeric_limits<streamsize>::max(), '\n'); //add this

Upvotes: 1

Related Questions