Thread: reading from file of unspecified size into array

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    30

    reading from file of unspecified size into array

    here is my attempted code so far but i have no idea to declare/read in for an uspecified sized array

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
    	ifstream infile;
    
    	int array[];
    	char fileName[21];
    	int number;
    	int total = 0;
    	int nums = 0;
    
    	cout << "Enter a file name: ";
    	cin >> fileName;
    
    	infile.open(fileName);
    
    
    
    
    
    
    	infile.close();
    	
    	return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You can't have an unspecified size array, let alone read into one. Presumably you intend to use vector.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    30
    "Write a program that asks the user for a file name. assume the file contains a series of numbers, each written on a separate line. the program should read the contents of the file into an array, and then display the following data...blablabla"

    so how could i do this?

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    30
    so here is my code knowing the number of numbers in the file...

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
    	ifstream infile;
    
    	int array[12];
    	char fileName[21];
    	int number;
    	int total = 0;
    	int nums = 0;
    	int size;
    
    	cout << "Enter a file name: ";
    	cin >> fileName;
    
    	infile.open(fileName);
    
    
    	for (int i = 0; i < 12; i++)
    	{
    		infile >> array[i];
    		total += array[i];
    	}
    
    	int lowest = array[0];
    	int highest = array[0];
    	for (int i = 0; i < 12; i++)
    	{
    		if (array[i] > highest)
    			highest = array[i];
    		if (array[i] < lowest)
    			lowest = array[i];
    	}
    
    	cout << "Total: " << total << endl;
    	cout << "Average: " << total/12 << endl;
    	cout << "Highest: " << highest << endl;
    	cout << "Lowest: " << lowest << endl;
    
    	infile.close();
    	
    	return 0;
    }

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    That's a very annoying assignment, since having the numbers in an array is completely useless for finding the total/average/highest/lowest.

    You can either (i) make one pass through the file just to count the number of numbers, and then use new/delete[] to make the array, (ii) break out malloc/realloc/free to get a chunk of memory and keep growing it until it is large enough (granted, then you don't actually have an array proper, but it is a contiguous chunk of memory just like an array is), or (iii) guess the size in advance and hope you're right. (Or (iv) use vector anyway, I suppose.)

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Unless you've learned some sort of dynamic array (using vector or new[]/delete[]) my guess is that you're supposed to just come up with some maximum size for the array. So assume that the file will have no more than 1000 entries or something like that.

    The thing you'd have to change with your code is identifying how to stop inputting. There is actually a simple technique for that.
    Code:
    while (infile >> array[i])
    That will loop while there are numbers in the file. You'll have to adjust the code to count the number of items properly, but that should be a good starting point. Another option is to use the same technique in an if statement combined with your current for loop so you can break out of the loop if the read fails:
    Code:
    if (!(infile >> array[i]))
    Last edited by Daved; 08-20-2009 at 07:18 PM.

  7. #7
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    Quote Originally Posted by tabstop View Post
    You can't have an unspecified size array, let alone read into one. Presumably you intend to use vector.
    I know I'll probably deserve a slap for writting this, either cause the idea unpheasable or its bad programming practice.

    BUT:

    Could you not use 'getch()' function to take a letter then attach it to a char pointer (sz)?
    That would aid in the 'unknown-size' issue surely?

    --------------

    NM. Doesnt help the matter at hand.

    Not to mention that I am refering to char types...
    Last edited by Else; 08-21-2009 at 05:44 AM.

  8. #8
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    838
    just find out what the size of the file is once you open a handle to it, then allocate an array off the heap of that size.

  9. #9
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    How I would have written this assignment in uni:

    Simply don't read it into an array. Then add a comment similar to this:
    Code:
    /**
     * Now, the assignment says I am to put all the data in an array. The
     * course description says, however, that the course is to learn C++,
     * and thus should exclude the teachings of bad practices. As an array
     * for reading the data into is not only completely useless, but makes
     * the program several times slower.
     * Hence, if this assignment is to prove the programmer's understanding
     * of dynamic allocation, this assignment is also filled with bad practices
     * and contrary to the course description. Otherwise, there is no reason
     * to read it into an array.
     */
    Summed up: If you want something to be used, mr. Professor, then get a ........ing assignment where it makes sense to use it.

    While I would do that in university I still managed to get high grades, even if I refused to do something the way they told me to. But then again, I did do some things on the side. So the first time we had to write some kind of computer AI for a game, everybody used the general brute force technique. My solution, using dynamic programming, was several orders of magnitude faster and could play the game game on a lot bigger boards or just a lot faster than my fellow student's solutions. I got a 10.5 out of 10 for that assignment (like 1 bonus point for doing it dynamically).

    So what I am trying to say here is that don't do what I said in this topic. That also concludes that there is no reason, except for my ultimate boredom, to actually post this. Or for you to read this. That also means I just wasted a few minutes (seconds if you're a fast reader) of your time.

    Like I said, you shouldn't do this unless you're already a competent programmer who can get away with it by making up for it by making the solution more clever. But on such an assignment like this, you can't really be more clever. Meaning, again, that it's a bad assignment.
    That's why I always hated school.


    Excuse me for wasting your time, if you read this.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Else View Post
    Could you not use 'getch()' function to take a letter then attach it to a char pointer (sz)?
    That would aid in the 'unknown-size' issue surely?
    Even ignoring the fact that the question concerns values of type other than char, you deserve a slap for the above.

    getch() is not a standard function in C or C++. It is a system specific extension supported only with some compilers/libraries.

    A pointer is not the same thing as an array. Whenever I see code that attempts to "attach" a letter to a char pointer, the actual consequence is undefined behaviour. Typical symptoms of undefined behaviour are little problems .... like programs crashing, data being corrupted, hard disks being accidentally reformatted, etc.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  11. #11
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    just find out what the size of the file is once you open a handle to it, then allocate an array off the heap of that size.
    This seems the most obvious solution to me as well. If the file contains numbers that are all of the same data type and there is no header to the file then figuring out how many numbers are in the file based on file size is a snap.

    But you could use a vector and then copy the vector to an array if you do not need vector's functionality later on - IE: if it's just a plain simple static array.

  12. #12
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I'm guessing, based on the fact that we're using >>, that the numbers are of the data type "typed in" -- i.e., in human-readable form -- and hence the byte count is an upper bound (actually you could probably get away with # of bytes/2, since there must be a space or a new-line or something in between the numbers).

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Given the code in the OP, I honestly think the solutions being discussed are too advanced. I'd be surprised if this user has even learned about dynamic arrays yet.

    If a dynamic array is desired, I don't see why you'd want to use anything other than vector. There's no benefit to allocating the array manually.

  14. #14
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    There's no benefit to allocating the array manually.
    If you can be sure exactly how much memory your vector is allocating. From my experience with MS STL it appears that vector allocates memory in chunks. Therefore if you go just beyond it's chunk size it will allocate the entire next chunk even if you only need a few bytes of it. No big deal for most apps and most platforms but since I'm used to coding for an embedded system that must run 24/7/365 memory usage is a huge deal. So I wouldn't say there is no benefit to allocating manually but in this case I would agree even that is overkill.

    In fact it probably would take less time to code the thing right here in the thread than it has taken to discuss the various approaches to it. Code it up using various methods in this post and use whatever works best for what you need. All of the approaches discussed have some merit but in the end it's up to you the programmer to pick one and implement it. Obviously even I am running out of suggestions since I am now down to splitting hairs.
    Last edited by VirtualAce; 08-21-2009 at 08:50 PM.

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by m37h0d View Post
    just find out what the size of the file is once you open a handle to it, then allocate an array off the heap of that size.
    seconded
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading a txt file into an array: unexpected segfault
    By pistacchio in forum C Programming
    Replies: 3
    Last Post: 05-05-2009, 04:27 PM
  2. Reading from a file into an array
    By fmsguy06 in forum C Programming
    Replies: 6
    Last Post: 10-18-2008, 09:25 PM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Read size of data array when reading .txt data
    By Taquito in forum C Programming
    Replies: 13
    Last Post: 04-29-2007, 01:52 AM
  5. reading a file into an array
    By dantegl36 in forum C Programming
    Replies: 11
    Last Post: 12-02-2006, 12:23 AM