Jump to content

Request for a Small Bit of Code


CoolMaster

Recommended Posts

This is for a project but basically I need to use structs and arrays to "make a ordered list" of stuff, now the structs shouldnt be "too" bad

 

but it's the arrays part thats got me

 

were given a file like this

 

Dell 512 1.7 120

HP 1024 1.4 80

Compaq 1024 1.6 100

Toshiba 512 1.8 160

Lenovo 2048 1.5 120

 

basically computers on it with specs

I have to read this in (ok got that, opening the file working and everything)

 

but then I have to make a loop to store each thing into an array

 

 

So Far here's what i have(the arrays are labeled as such)

 

 

 

/* Matt Smith

Section <>

CS 215 */

 

 

 

 

 

#include <iostream>

#include <string>

#include <fstream>

 

using namespace std;

 

int main ()

{

string brand;

int memory,hard;

float proc;

const int MAX = 1;

string compname[MAX];

float cpuspec[MAX];

int mem[MAX];

int HDD[MAX];

ifstream filein;

string filename;

int ordertype;

 

cout << "Please enter a file name containing your list of computers: ";

cin >> filename;

filein.open(filename.c_str());

cout << endl << endl;

cout << "Please choose a parameter to sort computers by (ascending): " << endl;

cout << " 1.Brand 2.Memory" << endl;

cout << " 1.CPU 2.Storage" << endl;

cin >> ordertype;

int ct = 0;

while(filein)

{

filein >> brand;

compname[ct] = brand;

filein >> memory;

mem[ct] = memory;

filein >> proc;

cpuspec[ct] = proc;

filein >> hard;

HDD[ct] = hard;

 

cout << compname[ct] << " ";

cout << mem[ct] << " ";

cout << cpuspec[ct] << " ";

cout << HDD[ct] << " ";

cout << endl;

 

ct ++;

 

}

 

 

 

filein.close();

 

return 0;

}

 

 

 

 

OK now here's where the problem starts, it'll display this

 

Please enter a file name containing your list of computers: computerdata.txt

 

 

Please choose a parameter to sort computers by (ascending):

1.Brand 2.Memory

1.CPU 2.Storage

1

Dell 512 1.7 120

HP 1024 1.4 80

Press any key to continue . . .

 

so it's getting the first 2, but then I run into an win32 error and it wont go any further, before it'd just go to HP then get an error? what is causing the error? and does my loop seem to work ok? or am I doing something wrong, it basically will need to display and store each thing into it's appropriate array.

 

thx

Share this post


Link to post
Share on other sites

you have four order choices numbered 1, 2, 1, and 2... even though it's not used yet

 

try commenting out the while loop /* before */ after and read just the brand, then display it... the way you're reading the file looks odd to me, as I'd read a line at a time

Share this post


Link to post
Share on other sites

I tried that out and it will display the first set of data correctly (dell 512mb etc.)

 

but if I put back in the loop it will only go to 2 sets this get an error. Maybe Ill email my prof and see what he thinks.

if anyone has any ideas tho let me know

Share this post


Link to post
Share on other sites

It's been awhile since my last C++ class, but maybe I can help...

 

The way you're reading the file is definitely a little strange. Is this the full code or did you remove some of it?

 

What I would do is read in a line of code, stick it into an array, then stick all the arrays into another array. Now sorting should be easy. :thumbs-up: If you don't know how to sort an array, just google "c++ array sort" and you'll find millions of hits.

 

Try reading in a line/array and then immediately spitting it out. I know that PHP has a print_r() function that takes arrays as input and prints them, hopefully C++ has something similar. And I would definitely change your sorting parameters to 1-2-3-4 instead of 1-2-1-2.

 

I just had another thought. Reading in a line from the file and then splitting it should be easy because the lines are all space delimited. Just use find() and substr(). ;)

 

So yeah, I hope some of my rambling is helpful.

Share this post


Link to post
Share on other sites

woops max was meant to be set to 10 ehehehe

 

 

YAY IT WORKS....sorta

 

 

Please enter a file name containing your list of computers: computerdata.txt

 

 

Please choose a parameter to sort computers by (ascending):

1.Brand 2.Memory

1.CPU 2.Storage

1

Dell 512 1.7 120

HP 1024 1.4 80

Compaq 1024 1.6 100

Toshiba 512 1.8 160

Lenovo 2048 1.5 120

Lenovo 2048 1.5 120

Press any key to continue . . .

 

prints the last one twice.........hmmmm?

 

just need it not to display that last once twice hmm.

Edited by CoolMaster

Share this post


Link to post
Share on other sites

Hmmm... brain fart. :D Just ignore that post. I keep thinking you're reading the whole line and then splitting it. That's the way I'd do it.

 

Take a look at how the files/lines are read in this program, it might be helpful. Just in case anyone is curious, this was an assignment for my C++ class a couple years ago. This is way more than you need to do, but some of the methods are still applicable. Let me know if you want the entire ZIP file.

 

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

using namespace std;

//function prototype(s)
bool compare(string);
void simplify();
bool correctComponents(string&);

int main()
{
ifstream inOrder;		//read orders
ofstream outPassed;		//write good orders
ofstream outFailed;		//write failed orders
ifstream inTemp;
ofstream outTemp;
string order,comp,temp;	//order (line), component
int pos,length;			//position, length of substring for component
int failCount = 0;		//number of failed orders
int passCount = 0;		//number of passed orders
int correctedCount;		//number of corrected orders
bool valid;				//valid order?
bool corrected;			//corrected order?

//simplify dictionary file
simplify();

//open files for read/write
inOrder.open("Orders.txt");
outPassed.open("PassedOrders.txt");
outFailed.open("FailedOrders.txt");
outTemp.open("temp.txt");

while(!inOrder.eof())
{
	getline(inOrder,order);	//read line from file

	corrected = false;

	//add a space at the end of the line if it doesn't exist
	if(order.substr(order.length() - 1,1) != " ")
	{
		order = order + ' ';
	}

	pos = 0;	//reset position to 0

	while(pos < order.length())
	{
		//find individual components from order list
		length = order.find(' ',pos + 1) - pos;
		comp = order.substr(pos,length);

		//compare order component to dictionary
		if(compare(comp))
		{
			valid = true;
		}
		else
		{
			if(correctComponents(comp))
			{
				//replace invalid component with vaild one
				order.replace(pos,comp.length(),comp);
				corrected = true;
				valid = true;
			}
			else
			{
				valid = false;
				break;	//stop checking order
			}
		}

		//find beginning of next component
		pos = 1 + order.find(' ',pos);
	}

	//if the order was corrected, write to file to be counted later
	if(corrected == true)
	{
		outTemp << order << endl;
	}

	//if order is valid
	if(valid == true)
	{
		//write to "passed" file
		passCount++;
		outPassed << order << endl;
	}
	else
	{
		//write to "failed" file
		failCount++;
		outFailed << order << endl;
	}
}

outTemp.close();
inTemp.open("temp.txt");

//count number of corrected orders
correctedCount = -1;
while(!inTemp.eof())
{
	getline(inTemp,temp);
	correctedCount++;
}

cout << showpoint << fixed << setprecision(2);
cout << "Good Orders: " << passCount << endl;
cout << "Bad Orders: " << failCount << " (uncorrectable)" << endl;
cout << "Corrected Orders: " << correctedCount << endl << "-----" << endl;
cout << "Corrected " << (float(correctedCount) / (correctedCount + failCount)) * 100 << "% of bad orders." << endl << endl;

inTemp.close();
inOrder.close();
outPassed.close();
outFailed.close();

//delete temporary dictionary file
remove("Dict_temp.txt");
remove("temp.txt");

return 0;
}



//compare order components to dictionary
bool compare(string comp)
{
ifstream inDic;				//dictionary file
int pos,length;				//position, length of substring for component
string definition,compDic;	//definition (line), dictionary component

//open simplified dictionary
inDic.open("Dict_temp.txt");

while(!inDic.eof())
{
	getline(inDic,definition);	//read line from file

	pos = definition.find("{") + 1;	//reset position

	while(pos < definition.length())
	{
		//find individual components from dictionary list
		length = definition.find(',',pos + 1) - pos;
		compDic = definition.substr(pos,length);
		pos = 1 + definition.find(',',pos);

		//if the component matches the dictionary, return 'true'
		if(comp == compDic)
		{
			return true;
		}
	}
}

inDic.close();

//return false if component doesn't match dictionary
return false;
}



//simplify dictionary file
void simplify()
{
ifstream inDic;				//dictionary file
ofstream outDic;			//simplified dictionary file
string tempStr;
int tempInt = 0;

//open dictionary files for reading/writing
inDic.open("Dict_Orig.txt");
outDic.open("Dict_temp.txt");

while(!inDic.eof())
{
	getline(inDic,tempStr);	//read line from file
	tempInt = 0;

	while(tempInt < 1)
	{
		//if " or " is in tempStr
		if(tempStr.find(" or ") <= tempStr.length())
		{
			//replace " or " with ","
			tempStr.replace(tempStr.find(" or "),4,",");
		}
		else
		{
			tempStr.replace(tempStr.length() - 1,1,",");	//replace end "}" with ","
			outDic << tempStr << endl;						//write line to file
			tempInt = 1;									//break out of loop (read next line)
		}
	}
}

outDic.close();
inDic.close();
}



//correct invalid components
bool correctComponents(string& comp)
{
int posC = 0;	//position for character comparison
int pos = 0;	//position for definition read
int charCount = 0;	//counts number of correct characters
int length;
string definition;
string compDic;
ifstream inDic;

inDic.open("Dict_temp.txt");

while(!inDic.eof())
{
	getline(inDic,definition);	//read line from file

	pos = definition.find("{") + 1;	//reset position

	while(pos < definition.length())
	{
		//find individual components from dictionary list
		length = definition.find(',',pos + 1) - pos;
		compDic = definition.substr(pos,length);
		pos = 1 + definition.find(',',pos);

		//reset character counters
		posC = 0;
		charCount = 0;

		//while character position is less than comp length
		while(posC < comp.length())
		{
			if(comp.substr(posC,1) == compDic.substr(posC,1))
			{
				charCount++;
			}

			if(charCount >= 2)
			{
				comp = compDic;
				return true;
			}

			posC++;
		}
	}
}

return false;
}

Share this post


Link to post
Share on other sites

thats alot of stuff im not that advanced yet :(

i just need to know how to get rid of that last display

and put it into a struct?

I probably shouldn't have posted the entire thing... :unsure:

 

This is the part I was talking about:

while(!inOrder.eof())
 {
	 getline(inOrder,order);	//read line from file

 

That saves the entire line as "order" (string variable). From there, it's easy to use order.find() and order.substr() to isolate the specs and put them in an array/struct.

 

When you read the entire line at once, it puts the cursor at the beginning of the next line. After the last line, the eof() function returns true and it jumps out of the while loop. The way you have things right now, the cursor is sitting at the end of the last line of text, not the end of the file, when the program checks to see if the file is finished reading. I would expect the variables to be replaced with null or empty strings during the final loop, but apparently the function doesn't change the variables at all and they keep their values. That's why you get the last line twice.

 

I hope that helps clear things up.

Edited by Bleeble

Share this post


Link to post
Share on other sites

It's been awhile since I've done C++(and hated every minute of it) But why limit your array to only 11 places.If it was me I would have it read in the number of lines and assign that minus 1 to be the array. That way if you have a file with more than 11 lines the program wont crash.

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...