0

Hello

How do I create an array when the size of the array is unknown? IE; the size of the array will depend on the contents of a file I am reading, so sometimes the array will end up being 10 sometimes 100.

The way I have tried, is to make the array in a struct but then the input is not stored in the array when I read a file, maybe there is something wrong with my code?(see comment in code)

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

struct budget {
	double expenditures[20];
	double budget_limit;
};

budget stats;

// I have left out the menu + display functions coz they're irrelevant & cluttered
void read(budget stats);
void menu();
void display(budget stats);

int main()
{

	read(stats);
	menu();


	return 0;
}

void read(budget stats)
{
	int x;
	int counter = 0;
	ifstream infile;

	infile.open("data.txt");

	if (!infile)
	{
		cout << "Failed to open file";
	}

	infile >> stats.budget_limit;

	while (infile >> x) {
		infile.ignore(100, '\n');
		stats.expenditures[counter] = x;
		counter++;
	}

// when the program runs the expected output from the code below does not appear??
	for (int i=0; i<array_size; i++)
	{
		cout << "Purchase " << i+1 << ": " << stats.expenditures[i] << "\n";
	}                        
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by iamthwee
0

Or if you're not allowed to use vectors you can try your hand at a dynamic array using new and delete[], or take a guess at the largest possible size it will be and declare that.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.