Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2007
    Posts
    61
    Thanks
    10
    Thanked 0 Times in 0 Posts

    C/C++ - Reading a text file of numbers into single dimensional arrays

    I have a text file called int50.txt filled with integers.

    like this -

    3
    4
    12
    -12
    -10
    91



    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 ??

  • #2
    Regular Coder BrickInTheWall's Avatar
    Join Date
    Mar 2009
    Location
    Munich, Germany
    Posts
    139
    Thanks
    1
    Thanked 13 Times in 13 Posts
    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:

    Code:
    #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];
    		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;
    }
    Call me Brick, if you like!

  • #3
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    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.
    Last edited by oracleguy; 09-21-2009 at 02:00 AM.
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •