GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 19-Dec-2004, 23:36
crystalattice's Avatar
crystalattice crystalattice is offline
Aspiring author
 
Join Date: Apr 2004
Location: Japan (again)
Posts: 1,628
crystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nice

No output from loop function


In my program, I need to output both the row averages of a tabular file and the column averages. I can get the row averages just fine but not the column averages. The column function appears to not do a thing; no output at all, even from my debug statements. I thought that, since the idea is the same, I could just use a modified version of the row function but I guess I'm wrong.

As usual, I'm sure there's a simple explanation for it but I can't seem to figure it out. Anyone else have a suggestion? Thanks.

Input file
Code:
Students: 3 Scores: 9 88 95 82 93 87 97 78 90 85

Main.cc
CPP / C++ / C Code:
/*********************************************************************
*Purpose:  Determine the overall student scores and individual test scores
 *	from a file
***************************************************************************/
#include <iostream>
#include <string>
#include <vector>
#include "Table.h"

using namespace std;

int main()
{
	cout << "Enter name of file: ";
	string fileName;
	cin >> fileName;

	Table studScores;
	fill(fileName, studScores);
	print(cout, studScores);	//debug
	rowAvg(studScores);
	colAvg(studScores);
	return 0;
}

Table.h
CPP / C++ / C Code:
/******************************************************************
*Purpose:  Table.h contains the declarations for type Table.
***************************************************************************/
#include <vector>    // vector
#include <iostream>  // istream, ostream
#include <string>    // string
using namespace std;

typedef vector<double> TableRow;
typedef vector<TableRow> Table;

// --- output a Table via an ostream
void print(ostream& out, const Table& aTable);

// --- fill a Table with values from a file,
//      whose first line is the # of rows & columns
void fill(const string& fileName, Table& aTable);

// --- fill a Table with values from a file
//      (without the limitation of fill())
void load(const string& fileName, Table& aTable);

//----Determine average of a row in the table
void rowAvg(const Table& aTable);

//----Determine average of a column in the table
void colAvg(const Table& aTable);

Table.cc
[c]
/************************************************** ************************
*Purpose: Table.cpp defines various Table operations.
************************************************** *************************/
#include "Table.h"
#include <fstream> // ifstream
#include <cassert> // assert()
using namespace std;

void print(ostream& out, const Table& aTable)
{
for (int row = 0; row < aTable.size(); row++)
{
for (int col = 0; col < aTable[row].size(); col++)
out << aTable[row][col] << '\t';
out << endl;
}
}

void fill(const string& fileName, Table& aTable)
{
ifstream in(fileName.data()); // open stream to file
assert(in.is_open()); // verify

int students, scores; // input variables for dimensions
string student_num, score_num; //input variables for text values in file
in >>student_num >> students >> score_num >> scores; // read dimensions
int rows = students, cols = scores/students;

Table locTable(rows, TableRow(cols)); // construct local table with
// correct # rows and columns
for (int r = 0; r < rows; r++) // for each row
for (int c = 0; c < cols; c++) // input cols values into row
in >> locTable[r]
CPP / C++ / C Code:
;
									// assign locTable to aTable so
	aTable = locTable;                     //   it has correct dimensions
	in.close();                            // close stream
}

void load(const string& fileName, Table& aTable)
{
	ifstream in(fileName.data());          // open stream to file
	assert(in.is_open());                  // verify

	Table locTable;                        // empty local table
	double aValue;                         // input variable
	char separator;                        // to test for '\n'

	for (;;)                               // loop:
	{
		TableRow aRow;                      //   start with an empty row
		for (;;)                            //   loop:
		{
		separator = in.peek();           //      peek at the next char
		if (separator == '\n') break;    //      if at end of row, exit
		in >> aValue;                    //      read a value
		if (in.eof()) return;            //      if eof, quit
		aRow.push_back(aValue);          //      append value to row
		}                                   //   end loop
		in.get(separator);                  //   consume the newline
		locTable.push_back(aRow);           //   append row to table
	}                                      // end loop

	aTable = locTable;                     // assign locTable to aTable
	in.close();                            // close stream
}

void rowAvg(const Table& aTable)
{
	int row = 0;
	while (row <=aTable.size())		//increment through each row in table
	{
		double row_sum = 0, row_avg = 0;
		for (int col = 0; col < aTable[row].size(); col++)	//increment columns
			row_sum += aTable[row][col];	//get the sum of each row
		row_avg = row_sum / aTable[row].size();		//get the average of each row
		cout << "The average score for student #" << row << " is " << row_avg << endl;
		row++;	//move to next row
	}
}

void colAvg(const Table& aTable)
{
	int col = 0, row = 0;
	while (col <= aTable[row].size())		//increment through each column in table
	{
		double col_sum = 0, col_avg = 0;
		for (row; row <= aTable.size(); row++)	//increment rows
		{
			cout << "Row #" << row << endl;	//debug
			col_sum += aTable[row][col];	//get sum of each column
		}
		cout << "The sum of column #" << col << " is " << col_sum << endl;	//debug
		col_avg = col_sum / aTable.size();		//get average of each column
		cout << "The average score for test #" << col << " is " << col_avg << endl;
		col++;	//move to next column
	}
}
__________________
Start Programming with Python-A beginner's guide to programming and the Python language.
-------------
Common Sense v2.0-Striving to make the world a little bit smarter.
  #2  
Old 20-Dec-2004, 01:10
LuciWiz's Avatar
LuciWiz LuciWiz is offline
Moderator
 
Join Date: Jul 2004
Location: Cluj-Napoca (Romania)
Posts: 1,032
LuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the rough
First of all, I think it is a mistake to loop through the array from 0 up to and including array.size(); you should get an access violation there.
Second, I modified your colAvg to this:

CPP / C++ / C Code:
void colAvg(const Table& aTable)
{
	int col = 0, row = 0;
	cout << endl << aTable[row].size() << endl;
	int noOfColumns = aTable[row].size();
	while (col < noOfColumns)    //increment through each column in table
	{
		double col_sum = 0, col_avg = 0;
		for (row = 0; row < aTable.size(); row++)  //increment rows
		{
			cout << "Row #" << row << endl;  //debug
			col_sum += aTable[row][col];  //get sum of each column
		}
		cout << "The sum of column #" << col << " is " << col_sum << endl;  //debug
		col_avg = col_sum / aTable.size();    //get average of each column
		cout << "The average score for test #" << col << " is " << col_avg << endl;
		col++;  //move to next column
	}
}


You see, with every while loop, row gets incremented; when you get to the second loop, you test aTable[row].size(), but row is now greater than the last "good" row in the matrix. It probably evaluates to 0.

Your code works now. Try it!

Best regards,
Luci
__________________
Please read these Guidelines before posting on the forum

"A person who never made a mistake never tried anything new."
Einstein
Last edited by LuciWiz : 21-Dec-2004 at 01:05. Reason: there != their (I know that :))
  #3  
Old 20-Dec-2004, 21:39
crystalattice's Avatar
crystalattice crystalattice is offline
Aspiring author
 
Join Date: Apr 2004
Location: Japan (again)
Posts: 1,628
crystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nice
You're right, it was evaluating to '0'. It works now. Thanks!
__________________
Start Programming with Python-A beginner's guide to programming and the Python language.
-------------
Common Sense v2.0-Striving to make the world a little bit smarter.
 
 

Recent GIDBlogAccepted for Ph.D. program by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 14:12
Nested for loop with function Tori C++ Forum 11 08-Nov-2004 14:02
using vector or array oshiotse C++ Forum 4 16-Apr-2004 11:59
Revising Script style ?????? pepee MySQL / PHP Forum 4 14-Apr-2004 05:59

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 10:26.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.