Thread: Use vector instead of fixed-size array

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

    Use vector instead of fixed-size array

    Hello,
    This is has become a nightmare. I wrote a program that used two fixed-size arrays to read information from a text file that had a product number first and a price second. It was to use a linear search to find the product number the user entered from the keyboard to display that product number and corresponding price, (option a) or display the entire list (option b). Everything worked fine.

    Then I got ambitious and decided I wanted to use vectors instead of arrays so they could grow as inventory does without changing code. That is where I am suffering. I am confusing myself when I work through the algorithm. It seems that everything should work the same with just minor alterations, but that isn't the case, or so it has become with the mess I have created.

    Any help on telling me where I am going wrong would be huge. I just may go back to the fixed-size array and call it quits. I am running out of time for this class.

    Code:
    #include <iostream>	
    #include <fstream>
    #include <string>
    #include <cassert>
    #include <vector>
    using namespace std;
    
    int main()
    {
        // menu for user 
        const string MENU = "\nPlease select your inventory search option:"
                            "\n For a search by product number select A"
                            "\n For a list of the entire product line select B."
                            "\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("Inventory.txt");
        assert(readInFile.is_open());
        // item number from inventory list
        vector<int> productNumber;
        vector<double> productPrice;
    
        int n = 0;
        while (readInFile >> productNumber[n] >> productPrice[n])
        {
            if (readInFile.eof()) break;
            n++;
        }
    
        for(;;)	
        {
            char userChoice;
            cin >> userChoice;
            switch (userChoice)
            {
                case 'A':
                case 'a':
                    cout << "\nEnter the product number:  ";
                    int pNumber;
                    cin >> pNumber;
                    for (int i = 0; i < productNumber.size(); i++)
                    {
                        int itemNum = productNumber[i];
                        if(itemNum == pNumber)
                        cout << productNumber[i] << productPrice[i] << "\n";
                    }
                    break;
                case 'B':
                case 'b':
                    cout << "\nCurrent Inventory and Prices:\n\n";
                    for (int i = 0; i < productNumber.size(); i++)
                        cout << "\t" << productNumber[i]<< productPrice[i] << "\n";
                    break;
               default:
                   cout << "\nInvalid selection.  Please try again."
                          << MENU;
            }
            break;
        }
        readInFile.close();
        cout << "\n";
        return 0;
    }
    Last edited by clegs; 09-16-2007 at 07:02 PM.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    i will take a look at the code, but before i do:
    Quote Originally Posted by clegs
    I can't get beyond compiler errors.
    please post any compiler errors.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    I changed my type on pNumber and itemNum to int which matched the vector type so I have been able to compile now. But I get an:
    An exception 'Unhandled Win32 Exception' has occured in ...
    error now. I have never encountered one of these in any of the code I have written. I really don't know where I have gone wrong now.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    A vector starts out with a zero size if you don't provide an initial one for it. That means that productNumber and productPrice are empty at first. Then, you use while (readInFile >> productNumber[n] >> productPrice[n]). But using operator[] on a vector (or array) requires that it has an element at that position.

    You don't know what size the vector will be, so you cannot give it an initial size in this code. Instead, what you should do is read into temporary variables in that while control. Then, inside the loop, use push_back to add an element to each vector.

    You won't actually need the n variable either, since you can use productNumber.size() to count how many items were added after the loop ends. You also won't need the if (readInFile.eof()) break; code.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Code:
    while (readInFile >> productNumber[n] >> productPrice[n])
    {
        if (readInFile.eof()) break; //no point
        n++;
    }
    
    for(;;) //no point
    {
        ...
        break;
    }

  6. #6
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    OK Great!

    I did that and I get beyong the compiler errrors. My new code snippet on that is:

    Code:
    while (readInFile >> number >> price)
    	{
    		if (readInFile.eof()) break;
    		productNumber.push_back(number);
    		productPrice.push_back(price);
    	}
    But, now my switch case, at least for a which is all I am focusing on right now doesn't work. What am I missing there? I enter the productNumber and it breaks out of the program.


    I just inserted a for loop with a cout statement (see code below) to see if the vectors are populating and there is noting displayed, so I don't think my readInFile is populating my vectors as expected.

    Code:
    vector<int> productNumber;
    vector<double> productPrice;
    int number;
    double price;
    
    while (readInFile >> number >> price)
    {
        productNumber.push_back(number);
        productPrice.push_back(price);
    }
        for (int i = 0; i < productNumber.size(); i++)
            cout << productNumber[i] << productPrice[i];
    Last edited by clegs; 09-16-2007 at 07:50 PM.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> if (readInFile.eof()) break;
    Remove that line. Unless you have garbage at the end of your file, that line might cause your code to skip the last line and otherwise will do nothing. The code inside the while control checks for end of file correctly all by itself.

    >> I enter the productNumber and it breaks out of the program.
    As robwhit was trying to point out, you have a break at the end of your for (;;) loop which will cause it to always run only once. Perhaps you meant that break to be inside the switch as part of the default case?

    Does your code output the found product number and price before it exits? From what I can tell, if you are entering the data correctly it should. The only problem would then be that it exits after that one time because of the break.

  8. #8
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    I removed the two "nothing" statments as robwhit suggested and I edited my code as I said above but not getting what I need.

    I can repost what my new code looks like if needed. But, because the cout right after my while isn't sending anything to the screen I think that is where my issue is, still.

  9. #9
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    The following is what my Inventory.txt file looks like.

    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

  10. #10
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    i think it would be good if you could also post your complete and updated code, especially now that we can see what data you are working with

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Your input file indicates a problem. Your code reads in an int, then a double. It also skips over any whitespace (spaces, tabs, newlines) because that's what operator>> does automatically. But it doesn't skip over dollar signs. You need to add code to read in or ignore the '$'. The best choice would probably be to read it into a dummy variable since it is surrounded by whitespace that will be ignored by operator>> when you do that.

    As soon as the first dollar sign is read, that will put the readInFile stream into a fail state and nothing else will get read. Your vectors will be empty.

  12. #12
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    Here is the new and inproved, but not quite:

    Code:
    #include <iostream>	
    #include <fstream>
    #include <string>
    #include <cassert>
    #include <vector>
    using namespace std;
    
    
    int main()
    {
    
    	// menu for user 
    	const string MENU = "\nPlease select your inventory search option:"
    						"\n For a search by product number select A"
    						"\n For a list of the entire product line select B."
    						"\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("Inventory.txt");
    	assert(readInFile.is_open());
    	// item number from inventory list
    	vector<int> productNumber;
    	vector<double> productPrice;
    	int number;
    	double price;
    
    	while (readInFile >> number >> price)
    	{
    		productNumber.push_back(number);
    		productPrice.push_back(price);
    	}
    	for (int i = 0; i < productNumber.size(); i++)
    		cout << productNumber[i] << productPrice[i];
    		
    	char userChoice;
        cin >> userChoice;
    	
    	switch (userChoice)
    	{
    	case 'A':
    	case 'a':
    		cout << "\nEnter the product number:  ";
    		int pNumber;
    		cin >> pNumber;
    		for (int i = 0; i < productNumber.size(); i++)
    			if(pNumber == productNumber[i])
    				cout << productNumber[i] << productPrice[i] << "\n";
    		break;
    	case 'B':
    	case 'b':
    		cout << "\nCurrent Inventory and Prices:\n\n";
    		for (int i = 0; i < productNumber.size(); i++)
    			cout << "\t" << productNumber[i]<< productPrice[i] << "\n";
    		break;
    	default:
    		cout << "\nInvalid selection.  Please try again."
    			 << MENU;
    	}
    	readInFile.close();
    	cout << "\n";
    	return 0;
    }
    Sorry! I didn't take the time to clean up the tab and space issue. Not quite sure how to get it posted correctly from the copy and paste function.

  13. #13
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    Ok So what if I remove the '$' from my file and then use it in my cout as a string when I display the info? Is that the easiest fix?

  14. #14
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164
    I removed the '$' from each price entry and it prints. So that is the issue.
    I think that I can get teh rest to work from what I know. I will be back if I can't figure it all out.
    Thanks everyone!

  15. #15
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    since the text file doesnt have to be user-friendly, that may be the quickest fix. have your product number and price separated by a single space.

    if you leave it as-is, you could read in a double, then a string which would result in '101' and '$ 45.00' respectively, correct? again, i think editing the text file would be quickest. however, you should make it error-proof so whoever is editing the text file at any point, doesnt have to worry about following such a strict (ie "one space") template.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. size of array
    By goran00 in forum C Programming
    Replies: 38
    Last Post: 04-02-2008, 09:57 AM
  3. Little Array Difficulty
    By G4B3 in forum C Programming
    Replies: 16
    Last Post: 03-19-2008, 12:59 AM
  4. How do you use variable to initialize array size?
    By yougene in forum C Programming
    Replies: 11
    Last Post: 09-04-2007, 02:50 PM
  5. Maximum array size?
    By code2big in forum C Programming
    Replies: 2
    Last Post: 05-25-2004, 08:16 AM