#include <fstream>#include <vector>using namespace std;int main(){ vector <int> array; ifstream input; input.open("data.txt"); int temp; while (input.good()) { input >> temp; array.push_back(temp); } input.close(); for (int i=0; i < array.size(); ++i) cout << array << endl; cin.ignore();}
reading in an array from a .txt file
The istream extraction operator >> will ignore white space (tabs spaces, newlines), so just make your file uses one or more of these as delimiters for your data. If you do not know how many elements are in the file either store the number of elements in the file header, and allocate the array after you read the header, or use a vector instead of an array:
#include <algorithm>#include <vector>#include <iterator>#include <fstream>#include <iostream>int main() { std::vector<int> array; //load into vector copy(std::istream_iterator<int>(std::ifstream("a.txt")), std::istream_iterator<int>(), std::back_inserter(array)); //print out copy(array.begin(), array.end(), std::ostream_iterator<int>(std::cout, " "));}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement