reading in an array from a .txt file

Started by
11 comments, last by raptorstrike 19 years, 6 months ago
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 <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();}
Advertisement
#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, " "));}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

thanks you guys have given me alot of good ideas [grin]
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie

This topic is closed to new replies.

Advertisement