0

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
4
  • You haven't asked a question. Commented Dec 1, 2019 at 16:43
  • How do I input multiple values from the .txt file into my array? Looks like you are already doing that. What is is doing that you don't expect? Commented Dec 1, 2019 at 16:44
  • If this is not working at all maybe you put your text file in the wrong location or named it differently than you thought. Commented Dec 1, 2019 at 16:47
  • Your code does not check or care if your file was actually read or if it contains enough values. I expect your file was not read at all. Commented Dec 1, 2019 at 16:48

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.