Search code examples
c++arraysiostream

How to input multiple values from a txt file into an array C++


I am looking to input individual inputs of a .txt file into my array where each input is separated by a space. Then cout these inputs. How do I input multiple values from the .txt file into my array?

    int main()
{
    float tempTable[10];

    ifstream input;
    input.open("temperature.txt");

    for (int i = 0; i < 10; i++)
    {
        input >> tempTable[i];
        cout << tempTable[i];
    }

    input.close();

    return 0;
}

With what I have written here I would expect an input of the file to go according to plan with each value entering tempTable[i] however when run the program out puts extreme numbers, i.e -1.3e9.

The temperature.txt file is as follows:

25 20 11.2 30 12.5 3.5 10 13

Solution

  • Your file contains 8 elements, you iterate 10 times.

    You should use vector or list and iterate while(succeded)

    #include <vector>
    #include <fstream>
    #include <iostream>
    int main()
    {
        float temp;    
        std::ifstream input;
        input.open("temperature.txt");
        std::vector<float> tempTable;
        while (input >> temp)
        {
            tempTable.push_back(temp);
            //print last element of vector: (with a space!)
            std::cout << *tempTable.rbegin()<< " ";
        }
        input.close();
        return 0;
    }