简体   繁体   中英

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, ie -1.3e9.

The temperature.txt file is as follows:

25 20 11.2 30 12.5 3.5 10 13

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;
}

You can use boost::split or directly assing the descriptor to variables

std::ifstream infile("file.txt");

while (infile >> value1 >> value2 >> value3) {
    // process value1, value2, ....
}

Or use the other version

std::vector<std::string> items;
std::string line;

while (std::getline(infile, line)) {
    boost::split(items, line, boost::is_any_of(" "));
    // process the items
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM