View Full Version : C/C++ - Reading a text file of numbers into single dimensional arrays

09-20-2009, 05:39 AM
I have a text file called int50.txt filled with integers.

like this -


I also have 2 arrays with 3 integers each a[3], b[3].

I need to create a function, which populates array A with the first three elements, b with the next 3 elements.

Such that a[3] = {3,4,12} and b[3] = {-12,10,91}

OK..another thing I dont want to use pointer or reference variables. I specifically want to do this with local/parameters.

I already know how to do it using pointers, i.e. passing an array as a pointer to the function.

How do I do this ??

09-20-2009, 11:55 PM
simply read the contents from the file line by line and write them to an array. Here's an example. It's not the most elegant way to do it, but it works for me:

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
fstream file("textfile.txt");
int linecount = 0;
int tempArray[100];
int *finalArray;

while (!file.eof())
file >> tempArray[linecount];

cout << "Number of lines: " << linecount;

finalArray = new int[linecount];
for (int i = 0; i < linecount; i++)
finalArray[i] = tempArray[i];

// Print the array.
cout << endl << "The array:" << endl;
for (int i = 0; i < linecount; i++)
cout << finalArray[i] << endl;

// Perform some operation with array content.
int result = finalArray[0] + 3;
cout << "finalArray[0] + 3 = " << result;

delete[] finalArray;
int endP;
cin >> endP;
return 0;

09-21-2009, 01:58 AM
Arrays are always passed by reference, never by value. Your only choices are pointers or by reference. Even if you don't put the '&' in the function declaration, if it is an array, its automatically by reference.

And unless there is a specific reason for using an array, using a vector is a much better choice.