Arrays

Anyone on that can help with a question about storing units in an array?
Shoot
Can I ask you a question?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

// function prototypes
int OpenAndValidateInputFile (ifstream& textIn);
void ReadAndStoreInputFile (ifstream& textIn, char unitType, double utilityCharge);

int main ()
{
	//
	const int MAX = 500;										// maximum number of stored units in array

	// local variables
	ifstream textIn;											// input file stream variable
	char unitType = 0;											// unit type - 'R' residential or 'B' business
	double utilityCharge = 0;									// utility charge
	char ResidentialUnit [MAX];									// array for 'R' residential units
	char BusinessUnit [MAX];									// array for 'B' business units

	OpenAndValidateInputFile (textIn);							// function call

	ReadAndStoreInputFile (textIn, unitType, utilityCharge);	// function call

	system ("PAUSE");

}

int OpenAndValidateInputFile (ifstream& textIn)
{
    // open input file
    textIn.open ("UNITS.TXT");

	// check if file opens successfully
	// if not, print a warning and exit program from main with a return code 1
	if (!textIn.is_open ())
	{
		cout << "Failed to open input file UNITS.TXT" << endl;
		
		return 1;
	}
}

void ReadAndStoreInputFile (ifstream& textIn, char unitType, double utilityCharge)
{
	while (textIn.peek () != EOF)
	{
		textIn >> unitType;
		textIn >> utilityCharge;
	}

	if (unitType == 'R')
	{

}


Can anyone explain the process of storing units in an array?
As im sure you have noticed, I stopped the code at the if statement...
what I am attempting to do is open and validate a text file that contains an 'R' for residential units and a 'B' for business units, and next to the letter it has a utility charge..
i.e.
unitType
R 74.12
B 102.93
R 68.02
I am opening and validating, then reading the data line by line. What I need to do is if the unitType is R, it needs to be stored in the ResidentialUnit array, and if it is a B needs to be stored in the BusinessUnit array, for calculations later...
@Catfish2 - who did you want to ask a question?
Given
1
2
vector<double> BusinessUnit; 
vector<double> ResidentialUnit;  // btw your arrays held char, those 74.12 or 102.93 wouldn't store 

you could
1
2
3
4
5
6
7
8
while (textIn >> unitType >> utilityCharge
       && (unitType == 'B' || unitTYpe == 'R') )
{
    if(unitType == 'B')
         BusinessUnit.push_back(utilityCharge);
    else if(unitType == 'R')
         ResidentialUnit.push_back(utilityCharge);
}

Although parallel data structures are a major anti-pattern.

How about storing your data in a map:

map<char, vector<double>> Units;
so that you can populate it with a simpler
1
2
3
while (textIn >> unitType >> utilityCharge
       && (unitType == 'B' || unitType == 'R') )
    Units[unitType].push_back(utilityCharge);
// if not, print a warning and exit program from main with a return code 1
That return 1; won't change main()'s error code. So if you want to terminate the program at that point, use exit(1); instead.

Now, about the arrays. To me it appears that you want to store floating point values, not characters. You discard the R's and B's you read, you only need them to figure out in which array to put the values that follow.

So is this what you want?
1
2
3
	// float or double, the latter uses double the memory but is more accurate
	float ResidentialUnit [MAX];
	float BusinessUnit [MAX];


Then you need a counter for both arrays, to know the current position where to insert the data.
You increase the correct counter every time you add data to the array it describes.
And also check if the counter doesn't exceed the array's MAX limit.

Now, I don't know if using arrays is a requirement of this project, but if not a lot of hassle can be avoided by using std::vector.
http://cplusplus.com/reference/stl/vector/
I do have to use Array as a requirement for this project.

As for the char/float issue, you both are correct...i did think about that incorrectly and fr some reason was trying to store the R's...not the utility charge. Dumb.

The exit/return...I am NOT allowed to use "exit" I have to use return, but here are the instructions, I thought it was correct..but you may have helped me find an error :)
"When the program tries to open the data file, if the data file does not exist, the program should issue an error
message, and return from the main function with a return code of 1 (NOTE: This means that if the program
attempts to open the file from within another function, it will need to pass back information about the success or
failure to main, so main can exit properly)."
... and now I see OpenAndValidateInputFile() is missing a return statement outside the if(). (This should pop up as an error the moment you try to compile your program.)

OK so if you can't use exit() you can just check what OpenAndValidateInputFile() returns in an if() inside main():
1
2
	if (OpenAndValidateInputFile (textIn) == 1) // assuming it returns 0 for all OK
		return 1; // this exits main() as expected 
I am using VS Express 2010, it isn't having any issues compiling with the return statement as it is. Are you saying I need a return 1; where it is in the if statement if the file doesn't open, and ANOTHER one outside of the statement??
Yes, because that function needs to return an int.
So the question is: what value will the function return, if the if()'s body is never entered?

And I'm surprised you don't get an error...

Edit: my mistake, I just checked -- a warning is what you get.
Last edited on
I have a lot of experience processing horrible little input files, hope this helps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
using namespace std;

const int MAX = 500;                 // maximum number of stored units in array
double ResidentialUnit[MAX] = {0.0}; // array for residential unit charges, initialized to 0.0
double BusinessUnit[MAX] = {0.0};    // array for business unit charges, initialized to 0.0
const char RESIDENTIAL_UNIT = 'R';   // sentinel for residential unit charge
const char BUSINESS_UNIT = 'B';      // sentinel for business unit charge
const char *UNIT_FILE = "UNITS.TXT"; // unit file

bool ReadAndStoreInputFile (const char *unitFileName)
{
  ifstream textIn(unitFileName);
  if(textIn.is_open())
  {
    int ResidentialUnitIndex = 0, BusinessUnitIndex = 0;
    char unitType;
    double utilityCharge;
    while(textIn.good())
    {
      textIn.get(unitType);                                                                 // read unit type character
      while(textIn.peek() == 32) textIn.get();                                              // next character is a space, toss it out
      textIn >> utilityCharge;                                                              // read utilityCharge
      if(textIn.peek() != BUSINESS_UNIT && textIn.peek() != RESIDENTIAL_UNIT) textIn.get(); // feed through newline
      switch(unitType)                                                                      // cases are conditional to what unitType holds
      {
        case BUSINESS_UNIT:
        {
          BusinessUnit[BusinessUnitIndex] = utilityCharge;                                  // put utilityCharge in BusinessUnit
        } break;
        case RESIDENTIAL_UNIT:
        {
          ResidentialUnit[ResidentialUnitIndex] = utilityCharge;                            // put utilityCharge in ResidentialUnit
        } break;
      }
    }
  } else {
    cout << "Error opening input file: " << unitFileName << endl;                           // display error
    return false;                                                                           // return failure
  }
  return true;                                                                              // return success
}

int main()
{
  if(ReadAndStoreInputFile(UNIT_FILE))
  {
    cout << "Unit file processed." << endl;
  } else {
    cout << "Error processing unit file." << endl;
    return(1);
  }
	return(0);
}


Used this input file: "UNITS.TXT"
1
2
3
4
5
6
7
8
9
R 74.12
B 102.93
R 68.02
R 107.54
B 993.99
B 5.12
R 10.57
B 110.11
B 575.00
Last edited on
Hmmm...ill have to mess around with that a little bit and see if it makes sense to me. This is my first week even learning what an array is in C++ :/ CONFUSED when trying to figure out to pass through user defined functions.
I am wondering what line 23 means. Why are using the number 32?
32 is the number 2016 in base 10. (Which is the ASCII code for space.)
http://cplusplus.com/doc/ascii/

Yes, he could've written while(textIn.peek() == ' ') textIn.get(); for the same effect... oh well.
Topic archived. No new replies allowed.