Storing entire file in variable and pulling info out of that varaible

This is a discussion on Storing entire file in variable and pulling info out of that varaible within the C++ Programming forums, part of the General Programming Boards category; Hi All, I need to develop a function that opens a file, stores it in a variable, seaches the variable ...

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    47

    Storing entire file in variable and pulling info out of that varaible

    Hi All,

    I need to develop a function that opens a file, stores it in a variable, seaches the variable for certain information and outputs appropriate information.

    A couple questions here:

    1.) How do you store an entire file in a variable?

    2.) I know to use "find" for searching the variable for information, but how would I get the information that goes with what was entered? For example, I enter the item number of a product, in which the program does a cout of item name, item price, etc...

    Any direction would be greatly appreciated.

    bob2509

  2. #2
    Unregistered
    Guest
    I would recommend using a dynamic data structure such as a vector (probably the easiest), linked list, queue, or stack. Also, I would use struct representing individual products, using your example, as the elements. Example:

    struct product
    {
    int number;
    int name;
    int price;
    };

    int main()
    {
    vector<product> data;
    //the rest of your program here
    }

    This makes searching very easy. Just use your favorite search algorithm to find the element containing any given product number, and you can then regurgitate the name and price.

    -P. Siegel

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    For what it's worth, 'unregistered' provided an excellent response to your query.

    I'd like to think that it's not a rarity, but I like to give credit when it's due.

    Well done.

    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    47
    Sorry, but I'm a newbie, that makes no sense to me. This is what I'm trying to do:

    Code:
    ifstream inData;		// Holds product info.
    char inventorFile[256];	// for inventor.txt data
    string fileName;		// for user input
    
    while (loop < 1)
    {
       cout << endl << endl << " Please enter the name of file: ";
       cin >> fileName;
       inData.open(fileName.c_str());
    			
       // Get Data 
    		
          if (!inData)
          {
                cout << "\n\n File could not be found.  Try again.";
                inData.clear();
                loop = 0;              
           }
          else
                loop++;
    }
    
    while (! inData.eof() )
    {
       inData.getline (itemNumber, 100);
       cout << endl << inventorFile << endl;
    }
    Alls this does is print the file on the screen. I need to be able to search inventorFile for itemNumber and print the line itemNumber is found in. When I tried to do that I got a class error.

    Any help would be greatly appreciated.

    bob2509

    The problem here is I trying to get

  5. #5
    Registered User
    Join Date
    Apr 2002
    Posts
    47
    Sorry, the above while statement:

    while (! inData.eof() )
    {
    inData.getline (itemNumber, 100);
    cout << endl << inventorFile << endl;
    }

    SHOULD BE:

    while (! inData.eof() )
    {
    inData.getline (inventorFile, 100);
    cout << endl << inventorFile << endl;
    }

  6. #6
    Registered User WebSnozz's Avatar
    Join Date
    Oct 2001
    Posts
    102
    I think a map would be best for you.
    If the file has one data item per line, then getline will get the data item on that line, I prefer to use the string version of getline though
    string BufferedData;


    PHP Code:

    //add this at the top of your main
    #include <map>
    #include <string>
    //and this near the beggining of main
    //it says create a map, which is alot like an array except it gets bigger and smaller, and instead of looking up an item by a number you can look it up by an item number, or string, or anything you want that has comparison operators


    map<intstringproductList;
    //the KEY is an integer, which will be the product number, and the data being stored is the name, which will be a string


    //now lower down in the loop where you are getting the file read in we will put the data in the map

    int tempNum;
    string tempName;
    while (! 
    inData.eof() ) //I personally prefer inData.good() which is true whever eof is not reached AND there is no error, two birds in one stone and you don't have to use the ! operator

    inData>>tempNum;//assuming the number is first
    getline(inDatatempName);//this gets the name of the product, which can follow the item number on the same line I thin, You won't be needing that char array anymore
    //with this you'll be using a dynamic string, meaning you don't have to tell it how many chars, it gets bigger and smaller as needed
    //first parameter is the istream your reading from, second parameter is the string you want it stored in

    //now we take our data and put it into the map like so
    productList[tempNum]=tempName;
    }

    //now that'll take you through the file and get the numbers and names and store them in the map
    cout<<"Enter the item number you want to look up: ";
    cint>>tempNum;
    cout<<endl;
    cout<<productList[tempNum];//this will put out the product name that corresponds with the item number entered 
    you can also change map<int,string> to map<string,int>

    this would mean you would add to the map like so
    productList["Name of product"]=5635;
    similarly using variables
    productList[productName]=itemNumber;
    and look up like this
    cout<<productList[productNameImLookingFor];

    Hope that wasn't to much, as mentioned before you could use a structure for your product,
    PHP Code:
    //this would go in a header file or at the top of your cpp file above main, along with the #include stuff, just like an int contains 4 bytes of memory that represent a number you can make your own data types that consist of other data types that already exist
    struct productDataType
    {
    int itemNum;
    string name;
    double price;
    }

    int main(){

    map<intproductDataTypeproductList;//create the map

    productDataType OneSingleProductVariable;//create a product

    //the product contains an integer, a string, and a deceimal(double)

    OneSingleProductVariable.itemNum=19695;//the . operator accesses the piece of the product
    OneSingleProductVariable.name="Marshall Tube Amp";//pretend it's just a string and your assigning that string a value
    OneSingleProductVariable.price=1599.95;//and the same with the decimal

    //now I store all three variables into the map in one swift action
    productList[19695]=OneSingleProductVariable;

    //I hard coded the item number in there, in reality it'd be like this
    productList[OneSingleProductVariable.itemNum]=OneSingleProductVariable;
    //OneSingleProductVariable.itemNum returns the value stored in itemNum which is a part of OneSingleProd..Var

    //now to get the product back out you look it up by it's item number
    productDataType TemporaryProduct;
    TemporaryProduct=productList[19659];
    //this stores the product that is looked up by the item number into the temporary product, now you can output the parts like so

    cout<<TemporaryProduct.itemNum<<endl;
    cout<<TemporaryProduct.name<<endl;
    cout<<TemporaryProduct.price<<endl
    Good luck with that, It's late here and I hope I haven't made any serious goof ups, if you had posted your entire program I would have made it so that I could test it and make sure it compiled and ran
    WebSnozz-
    Cats have no butt cheeks.
    If one farted, then it would make a flute noise.

  7. #7
    Registered User
    Join Date
    Apr 2002
    Posts
    47
    I tried to put something together from what you came up with, but I got 5 very long errors that I am clueless about. Here's the code I came up with:

    Code:
    #include <iostream>				  // #include <map>
    #include <string>
    
    using namespace std;
    
    int main()
    {
    	map<int, string> productList;
    
    	int tempNum;
    	string tempName;
    
                    int loop = 0;
    	ifstream inData;					char inventorFile[256];				string fileName;					
    while (loop < 1)
    {
           cout << endl << endl << " Please enter the name of file: ";
           cin >> fileName;
           inData.open(fileName.c_str());
    			
    	// Get Data 
    		
          if (!inData)
         {
                cout << "\n\n File could not be found.  Try again.";
                inData.clear();
                loop = 0;              
          }
          else
                loop++;
          }
    
          while (! inData.eof() )
          {
               inData>>tempNum;
               getline(inData, tempName);
               productList[tempNum]=tempName;
           }
    
                    cout<<"Enter the item number you want to look up: ";
    	cin>>tempNum;
    	cout<<endl;
    	cout<<productList[tempNum]
    
        return 0;
    }

  8. #8
    Registered User WebSnozz's Avatar
    Join Date
    Oct 2001
    Posts
    102
    I added comments where I made corrections.

    Sorry, forgot to tell you about the warnings. Whenever you compile this you will get 95 warnings because the map library has some very long function names that get truncated by the compiler for the debugging names, but it won't affect the functoining of your program and if you change it to compile to a release version you won't get the error either.

    I'll add a preprocessor thingy to make it stop the warnings though

    PHP Code:
    #pragma warning(disable: 4786)//This tells it not to show us that stupid warning



    #include <iostream>
    #include <fstream>//you needed this in order to use ifstream     
    #include <string>
    #include <map>


    using namespace std;

    int main()
    {
        
    map<intstringproductList;

        
    int tempNum;
        
    string tempName;

                    
    int loop 0;
        
    ifstream inData;
    //deleted inventor file char array since it's not used
        
    string fileName;                    
    while (
    loop 1)
    {
           
    cout << endl << endl << " Please enter the name of file: ";
           
    cin >> fileName;
           
    inData.open(fileName.c_str());
                
        
    // Get Data 
            
          
    if (!inData)
         {
                
    cout << "\n\n File could not be found.  Try again.";
                
    inData.clear();
                
    loop 0;              
          }
          else
                
    loop++;
          }

          while (! 
    inData.eof() )
          {
               
    inData>>tempNum;
               
    getline(inDatatempName);
               
    productList[tempNum]=tempName;
           }

                    
    cout<<"Enter the item number you want to look up: ";
        
    cin>>tempNum;
        
    cout<<endl;
        
    cout<<productList[tempNum];//you were missing a semicolon here, you probably would have found it on your own had it not been for the huge warnings I forgot to tell you about, sorry again

        
    return 0;

    and this is what the text file looked like I tested with

    4568 Jimi Hendrix's Fart Gas in a bottle
    57657 Get it while it's fresh, Bob Dylans fart gas in a milk carton
    464 You can't beat President Lincoln's fart in an antique teapot, sceintifically proven it's his

    Program output::


    Please enter the name of file: test.txt
    Enter the item number you want to look up: 4568

    Jimi Hendrix's Fart Gas in a bottlePress any key to continue





    Good luck

  9. #9
    Registered User WebSnozz's Avatar
    Join Date
    Oct 2001
    Posts
    102
    Just to clarify, it's the fart that is scientifically verified that Lincoln is the owner, we aren't sure the teapot is his, he was probably leaving a surprise for someone else.
    WebSnozz-
    Cats have no butt cheeks.
    If one farted, then it would make a flute noise.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21