Thread: Read data from file and store in array

  1. #1
    Registered User
    Join Date
    Sep 2020
    Posts
    11

    Read data from file and store in array

    Hello. I am trying to read data from a file into 2 different arrays. I store the company name, symbol, and price into a class array named stocks. Then I store the frequency into and array name freq. The problem is I can't seem to read the file correctly. I used Visual Studio's debugger and it looks like every element in the stock array is the same, and for some reason it only reads the first frequency in the file and not the rest.

    Here are a few lines from the file I'm reading:
    Code:
    Apple Inc.
    AAPL 114.95
    0.1
    Amazon.com, Inc.
    AMZN 15.46
    0.1
    And then here is the code I am having trouble with:
    Code:
            ifstream file;
        string name;
        string symbol;
        double price;
        double frequency;
        const int numStocks = 10;
    
    
        Stock stocks[numStocks];
        double freq[numStocks];
    
    
        //read file into arrays
        file.open("stock.txt");
        if (!file)
            cout << "Can't open file\n";
    
    
        int i = 0;
        while (getline(file, name))
        {
            stocks[i].setName(name);
            file >> symbol;
            stocks[i].setSymbol(symbol);
            file >> price;
            stocks[i].setPrice(price);
            file >> frequency;
            freq[i] = frequency;
            //file.ignore();
            file.ignore(1000, '\n');
            ++i;
        }
    
    
        file.close();
    Any help is appreciated.

  2. #2
    Registered User
    Join Date
    Sep 2020
    Posts
    11
    Hello everyone. I was able to fix my code thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to read file and store into an array
    By ec661 in forum C Programming
    Replies: 5
    Last Post: 05-06-2019, 02:47 AM
  2. Read Strings in from text file and store into array
    By RRTT in forum C++ Programming
    Replies: 4
    Last Post: 12-13-2011, 04:52 AM
  3. Read text file, scan and store data into variables?
    By wisdom30 in forum C Programming
    Replies: 8
    Last Post: 04-18-2011, 11:23 PM
  4. Read text file and store it in an array
    By look2hook in forum C Programming
    Replies: 2
    Last Post: 12-03-2010, 11:47 PM
  5. read and store text file as an array
    By abotaha in forum C++ Programming
    Replies: 1
    Last Post: 08-02-2010, 08:57 PM

Tags for this Thread