1

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
1
  • Not really clear. When you comment out what line what will happen? The code you posted will print what? Oct 10, 2016 at 14:01

1 Answer 1

1

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
1
  • Thank. Do you know of any links that explains the how and why of this?
    – Elchanan
    Oct 10, 2016 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.