<fstream>and Array question

Hey everyone! I need to make a project for my CIS class and I was wondering if anyone could help me by giving me a snippet of code or so or some example of how to read a files data into an array. I am pretty familiar with f stream, and with arrays as well. I just can't figure out how to connect the too...an example of what I mean:


External file.txt containing numbers:

1, 2, 3, 4, 5




1
2
3
4
5
6
7

int myArray[5];


//Code to input file elements into array.
cout <<
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
	string fileName("External file.txt");
	ifstream inFile(fileName.c_str());

	while(!inFile.is_open())
	{
		cout << "The file \"" << fileName << "\" not found. Enter another file : "; 
		getline(cin, fileName);

		inFile.open(fileName.c_str());
	}
	cout << "The file \"" << fileName << "\" has been opened successfully." << endl;

	int i;
	int size = 0;
	int myArray[500];
	while(inFile >> myArray[size]) size++;

	cout << "The five array elements are : ";

	for(i = 0; i < size; i++)
	{
		cout << myArray[i];
		if(i < (size - 1)) cout << ", ";
	}
	cout << endl;

	inFile.close();
	cin.get();
	return 0;
}


The file "External file.txt" has been opened successfully.
The five array elements are : 1, 2, 3, 4, 5
Last edited on
Wow thank you! That really helped. Wasn't expecting such a fast response.

Thanks again!
Topic archived. No new replies allowed.