Thread: Using Vectors (cont) - Sort Problem

  1. #1
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164

    Using Vectors (cont) - Sort Problem

    Hello again,
    This is a continuation of the vector vs fixed-size array issue because I couldn't let it alone.

    I got the code to work as it should using vectors instead of fixed-size arrays, but I didn't like the product numbers displayed out of order, for selection 'B.' So, I decided to try a sort. After thinking about it for a while, I figured out a way but there is an MDE error that I am getting and don't know how to fix it. I should say I am using Visual Studio 2003.

    The sort happens and the display is correct, but the new text file isn't populated until I hit the yes button on the pop-up box.

    I have the file sort function call at the very top of main() and the function outside of main at the end. I tried a similar sort all by itself in another project and everything worked fine, so I think that it is because it is inside of main and doesn't close before being used in main(). But, I am not sure.

    Can anyone help?

    This is my code:

    Code:
    #include <iostream>	
    #include <fstream>
    #include <string>
    #include <cassert>
    #include <vector>
    #include <iomanip>
    #include <algorithm>
    using namespace std;
    
    int fileSort();
    
    int main()
    {
    	fileSort();
    
    	// menu for user 
    	const string MENU = "\nPlease select your inventory search option:"
    						"\n A - To search by product number"
    						"\n B - To display a list of the entire product line."
    						"\n Enter your selection ===>  ";
    	// program banner
    	cout << "\nThis program queries the inventory list of Rinky Dooflingy Co."
    		 << "\nfor the price by item number or it displays the entire inventory"
    		 << "\nlist.\n"
    		 << MENU;
    	//read in inventory file
    	ifstream readInFile("InventorySort.txt");
    	assert(readInFile.is_open());
    	// vector and temporary variable declarations
    	vector<double> productNumber;
    	vector<double> productPrice;
    	double number;
    	double price;
    	// read data in from file to two temporary variable holders
    	while (readInFile >> number >> price)
    	{
    		// populate vectors with new variable data
    		productNumber.push_back(number);
    		productPrice.push_back(price);
    	}
    	// request menu option from user
    	char userChoice;
        cin >> userChoice;
        // display data as user requested    
    	switch (userChoice)
    	{
    		// prompt user for item number
            case 'A':
    		case 'a':
    			cout << "\nEnter the product number:  ";
    			// get item number
    			double pNumber;
    			cin >> pNumber;
    			// search through productNumber data for item number match
    			for (int i = 0; i < productNumber.size(); i++)
    				if(pNumber == productNumber[i])
    					// display data if a match is found
    					cout << "\n\t" << "Item: " << setprecision(0) << productNumber[i]
    						 << "   Price: $" << right << fixed << setprecision(2) 
    						 << setw(8) << productPrice[i] << "\n";
    			break;
    		// display entire inventory list
    		case 'B':
    		case 'b':
    			cout << "\nCurrent Inventory and Prices:\n\n";
    			for (int i = 0; i < productNumber.size(); i++)
    				cout << "\t" << "Item: " << setprecision(0) << productNumber[i]
    					 << "   Price: $" << right << fixed << setprecision(2) 
    					 << setw(8) << productPrice[i] << "\n";
    			break;
    		default:
    				cout << "\nInvalid selection.";
    	}
    	readInFile.close();
    	cout << "\n";
    	return 0;
    }
    
    
    int fileSort()
    {
        ifstream inStream("Inventory.txt");
    	assert(inStream.is_open());
    	vector<string> inventoryVector;
    	string inventoryLine;
    	for (;;)
    	{
    		getline(inStream, inventoryLine);
    		if (inStream.eof()) break;
    		inventoryVector.push_back(inventoryLine);
    	}
    	inStream.close();
    
    	sort(inventoryVector.begin(), inventoryVector.end());
    
    	ofstream outStream("InventorySort.txt");
    	assert(outStream.is_open());
    	for (int i = 0; i < inventoryVector.size(); i++)
    		outStream << inventoryVector[i] << endl;
    	outStream.close();
    	return 0;
    }
    This is the instream text file "Inventory.txt":

    Code:
    101      45.00
    303        3.00
    707    102.00
    302      13.45
    555        7.97
    999    500.00
    345      76.99
    325        3.33
    769      22.45
    111        2.76
    Once the program ends. A Microsoft Development Environment box pops up and refering to the InventorySort.txt file, says:
    "This file has been modified outside of the source editor. Do you want to reload it."

    The file has been sorted, it just hasn't been written to the text file - the file is blank unless I say yes. What is happening, why, and how do I fix it?

    Thanks for your input. You all have been great!

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    So it sorts the file but visual studio doesn't refresh it until you tell it to. I don't see the problem.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by clegs View Post
    Once the program ends. A Microsoft Development Environment box pops up and refering to the InventorySort.txt file, says:
    "This file has been modified outside of the source editor. Do you want to reload it."

    The file has been sorted, it just hasn't been written to the text file - the file is blank unless I say yes. What is happening, why, and how do I fix it?

    Thanks for your input. You all have been great!
    That's not a problem, it appears that you have the input file (InventorySort.txt) open in your IDE. When you modify a file outside of the control of the IDE, any file that you have open within the IDE, you'll get that message. It's just the IDE's way of letting you know that some other process has altered one of the files you have open and letting you make a decision on whether or not you want that file to be updated to match the current version. You can "fix it" by not having a window open for that file in your IDE.

    A big problem is that your fileSort function does the wrong thing to your file. It reads the existing file, product number and price, but then after the sort, it writes the information with only the product number but no price. Even if you do this sort, it is going to be difficult to keep the price vector sorted in a way that keeps the correct price associated with the correct product number. Think about it, you sort the product number but not the prices, so that what was in productNumber[0] might now be in productNumber[4] (for example) but what about productPrice[0]? Does is get moved to productPrice[4] as well?

    There are different things you can do:

    1) Instead of storing your file information in 2 different vector<double>'s, you can store a struct that contains the product number and price into a single vector. For this to work, your program is also going to need a custom sorting function object that can be passed to the sort function since the default (operator<) is no longer going to work, or you'll need to overload the less-than operator. Now, when the vector is sorted, the price and product number would get sorted together.
    Code:
    struct product
    {
        int number;
        double price;
        product(int num = 0, double pri = 0.0) : number(num), price(pri) {}
    };
    
    bool operator<(const product& lhs, const product& rhs)
    {
        return lhs.number < rhs.number;
    }
    
    istream& operator>>(istream& is, product& rhs)
    {
        return is >> rhs.number >> rhs.price;
    }
    
    ostream& operator<<(ostream& os, const product& rhs)
    {
        return os << rhs.number << ' ' << rhs.price;
    }
    
    void sortFile()
    {
        ifstream inStream("Inventory.txt");
        assert(inStream.is_open());
        vector<product> inventoryVector;
        product temp;
        while( inStream >> temp )
            inventoryVector.push_back( temp );
        inStream.close();
    
        sort(inventoryVector.begin(), inventoryVector.end());
    
        ofstream outStream("InventorySort.txt");
        assert(outStream.is_open());
        for (int i = 0; i < inventoryVector.size(); i++)
            outStream << inventoryVector[i] << endl;
        outStream.close();
    }
    That code also demonstrates operator overloading of operator< (to take care of the sorting requirements) and operator>> to be able to read a product object from the file, and operator<< to write the product object to a file. You can do without those last two if you do the reading and writing a bit differently.


    2) You can try a different container and skip the sortFile function altogether. Just read the data into a map<int,double> container instead of a vector. Information in a map is automatically sorted according to the key, which you would want to be the product number in this case.
    Last edited by hk_mp5kpdw; 09-17-2007 at 06:37 AM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compile problem: sort() cannot be used as a function!?
    By ac251404 in forum C++ Programming
    Replies: 2
    Last Post: 06-01-2006, 12:58 PM
  2. Problem with vectors and classes
    By applenerd in forum C++ Programming
    Replies: 6
    Last Post: 04-08-2006, 06:36 PM
  3. Problem with Bubble Sort code
    By lisa1234 in forum C++ Programming
    Replies: 7
    Last Post: 01-13-2004, 03:40 PM
  4. problem: cant acess class methods using vectors
    By justdoit22 in forum C++ Programming
    Replies: 8
    Last Post: 12-30-2003, 07:47 PM
  5. Decending Sort Problem
    By SledMan2002 in forum C Programming
    Replies: 4
    Last Post: 10-26-2002, 06:07 PM