outputting a partially filled array onto a text file

I have a partially filled array and I want to put that into a text file. Say I don't know how partially filled it is. How would I stop at the very end of the array where it has the last amount of data.

ex.
int array[9] = {1,2,5,6};

ofstream output("txt file");
for(int i = 0;i < 9; i++){
output << array[i]
}
How would I stop as soon as i becomes 4 because that is when the array stops?
You're going to have to determine how many entries are in the array.
You can do that a number of ways.
1) Count the number of items you put in the array. In the case of your example, that's easy since you have an initializer list of 4 values.
2) If you're prompting the user for values, or reading from a file, simply increment a counter every time you add a number.
3) Initialize the array to some unused value such as 0 or -1. Then count the number of values that are not that unused value.
4) Use a std::vector. The vector will keep track of how many items you add.

1
2
  int cnt = 4;  // Or however many items there are per one of the above methods
  for (int i=0; i<cnt; i++)


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
Topic archived. No new replies allowed.