By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 811 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

Question about arrays and file input...

P: 9
Say you have a .txt file with a random amount of numbers. Is there a way to initialize an array with that input file of numbers?

After telling the program to open the input file, "inputFile," I made an array called "Array[ ]" and tried to initialize it to the input file. It looks like this: "int Array[ ] = {inputFile};", but it obviously doesn't work. I get an error saying it cannot convert from 'std::ifstream' to 'int'. Are there any ways to go about this without actually assigning the array a constant value everytime the file is changed? I apologize if this is a stupid question, but I'm new to programming. :-/
Nov 2 '06 #1
Share this Question
Share on Google+
2 Replies

Expert 2.5K+
P: 3,652
Actually, this is a brilliant question - one that I recently had to tackle, and I'm in my third year of programming.

In C++, you normally need to provide a constant value when defining an array - either a number (like 5) or a constant variable. There is a way, however, to use a variable (that isn't constant) to determine the size - with pointers.

Pointers are a hard subject that still confuse me a bit, so for the sake of simplicity I'll just explain pointer arrays. Consider the following, non-pointer arrays:

Expand|Select|Wrap|Line Numbers
  1. const int SIZE = 5;
  3. int nums[10]; // Legal - numbers don't change and are constant
  4. int moreNums[SIZE]; // Legal - SIZE is constant
But you can't say

Expand|Select|Wrap|Line Numbers
  1. int evenMoreNums[x]; // Your compiler will hate you!
However, you CAN say

Expand|Select|Wrap|Line Numbers
  1. int *evenMoreNums;
  2. evenMoreNums = new int[x]; // Your compiler <3s you again!
The asterisk is important, as is the "new". Your x can be determined any way you want - evenMoreNums will hold that many values!

Perhaps someone else can explain pointers better than I can.
Nov 2 '06 #2

P: 9
Thanks for the reply. I couldn't quite figure out how to get pointers to work, so I went ahead and just assigned the array 11 elements, (I put 11 numbers in the .txt file). It will compile, but upon execution I get a run-time error saying "Stack around the variable 'Array' was corrupted." I'm not sure what that means. The program is kinda long (and probably reeks of a beginner), but if necessary I can post the code...
Nov 2 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.