Reputation: 2544
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
Upvotes: 0
Views: 941
Reputation: 8313
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;
}
Upvotes: 1
Reputation: 392
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
}
Upvotes: 0