Reading a txt file into a struct problem

This is a discussion on Reading a txt file into a struct problem within the C++ Programming forums, part of the General Programming Boards category; Hi, I have wrote a program which places the contents of three array's into a txt file. The 3 arrays ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Location
    U.K.
    Posts
    148

    Thumbs up Reading a txt file into a struct problem

    Hi,

    I have wrote a program which places the contents of three array's into a txt file.

    The 3 arrays (total of 10 different items):-

    char string (food's name)
    double (food's price)
    bool (is food's price over 5)


    Now instead of using the 3 arrays, I want to read contents from this txt file and place the contents into an array of structs.

    Being new to this, I'm just starting with trying to read the txt file, but the lines in bold below are causing me problems, and am looking for some help.

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    const int MAXCHARS = 20;
    const int MAXITEMS = 10;
    
    struct mystruct
    {
    	char itemname[MAXITEMS][MAXCHARS];
    	double price;
    	bool luxury;
    };
    
    int main()
    {
    	mystruct mystructname;
    
    	ifstream mystream("myfile2.txt");
    
    	if(!mystream)
    	{
    		cout << "phail " << endl;
    	}
    
    
    	mystream >> mystruct.price;
    
            cout << mystructname.price;
    		
    
    	mystream.close();
    
    
    	system ("pause");
    
    	return 0;
    Been struggling with all this all day, so any help will be a big help.

    Many thanks!

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    You need to create an array of mystruct. Right now, you have one mystruct, and inside there is one price, one luxury boolean and an array of MAXITEMS names. You want the names to be a single char array (because they are strings) and make an array of MAXITEMS mystructs.

    Then you can input into the array and access each member with something like mystructarray[index].price.

  3. #3
    Registered User
    Join Date
    Aug 2007
    Location
    U.K.
    Posts
    148
    Thanks Daved

    Like this ? :-

    Code:
    mystruct thestructsarrayname[MAXITEMS]; //this will be the array for the 10 structs

  4. #4
    Registered User
    Join Date
    Aug 2007
    Location
    U.K.
    Posts
    148
    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    const int MAXCHARS = 20;
    const int MAXITEMS = 10;
    
    struct mystruct
    {
    	char itemname[MAXCHARS];
    	double price;
    	bool luxury;
    };
    
    int main()
    {
    	mystruct mystructname;
    
    	mystruct thestructsarrayname[MAXITEMS]; 
    
    	ifstream mystream("myfile2.txt");
    
    	if(!mystream)
    	{
    		cout << "phail " << endl;
    	}
    
    	for(int i = 1;i < 10;i++)
    	{
    		cout >> thestructsarrayname[i].price;
    	}	
    
    	mystream.close();
    
    	system ("pause");
    
    	return 0;
    }
    I know it's easy to some people, I'm finding it hard to figure out as I've never done it before, and whenever I ask people for help (not Daved) they either say something I don't understand, or go wayy over my head saying use vectors, or overload this and that.

    If anyone could PLEASE just help me out with reading from the txt file so that the first food item goes into the first struct I would be EXTREMLY grateful. I appreciate just giving someone the answers isn't helpful, but being stuck with one issue for this long is not helpful either. I know my code may not be 'optimised', or have other issues I'm not aware of, but that's because I'm new to all this and trying to teach myself.

    Sorry for the long post, but I've become really frustrated with this, because I know that once I do have a working program, I'll be able to go through it slowly with the debugger step by step, and that way I'll get it into my head, it's just the way my brain works.

    Many many thanks to anyone who can help me with this.



    Swerve

    P.S. I've attached a screen shot of the txt file, because I don't understand how it knows which bit to read.
    Attached Images Attached Images  

  5. #5
    coder
    Join Date
    Feb 2008
    Posts
    127
    hi Swerve

    1:
    I'd suggest you to use better names for your variables/structures
    (avoid using "my" everywhere since it makes the code less readable).
    example:
    Code:
    struct Item {
    	char name[MAXCHARS];
    	double price;
    	bool luxury;
    };
    
    Item itemList[MAXITEMS];
    // instead of: mystruct thestructsarrayname[MAXITEMS];
    2:
    this line is useles: do you need the object instantiated here?
    Code:
    mystruct mystructname;
    3:
    Code:
    	if(!mystream)
    	{
    		cout << "phail " << endl;
    	}
    I would use:
    if (!mystream.good ())
    instead.
    Anyway, in case the fstream wouldn't be ok (eg: bad filename) your program should do something, like quit the program, instead of normally continue like you're actually doing.

    4:
    After the fstream test you do this:
    Code:
    	for(int i = 1;i < 10;i++)
    	{
    		cout >> thestructsarrayname[i].price;
    	}
    cout is an ostream (output stream) object of the STL which let you print something to the standard output.
    So you are not allowed to use it as an input stream.
    At the 3rd line of the main function you create mystream:
    Code:
    ifstream mystream("myfile2.txt");
    why don't use it to fill your struct array?
    Code:
    mystream >> variable;
    Your syntax was ok, but you were trying to use the wrong object.

    5:
    I'd finally suggest you to first try to read only one type of value:
    remove all numbers from the txt file and try to read only the item names.
    Then, once you get used with fstream, you can add the doubles and the bool values.
    Last edited by carlorfeo; 03-18-2008 at 02:35 AM.

  6. #6
    Registered User
    Join Date
    Aug 2007
    Location
    U.K.
    Posts
    148
    Thank you VERY much carlorfeo for taking the time to help me.

    I still can't get it to work, it just keeps saying:-

    \main.cpp(28) : error C2228: left of '.price' must have class/struct/union
    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    const int MAXCHARS = 20;
    const int MAXITEMS = 10;
    
    struct items
    {
    	double price;
    };
    
    int main()
    {
    	double itemlist[MAXITEMS];
    
    	ifstream mystream("myfile2.txt");
    
    	if(!mystream)
    	{
    		cout << "phail " << endl;
    	}
    
    	mystream >> itemlist;
    
    	for(int i = 0;i < 10;i++)
    	{
    		cout >> itemlist[i].price;
    	}	
    
    	mystream.close();
    
    	system ("pause");
    
    	return 0;
    }
    I've been looking at this code for so long now it's wrecking my head. I've got two books here and google and I just can't see 'it'.
    Last edited by Swerve; 03-18-2008 at 12:06 PM.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    Start even smaller. You seem to be throwing code in and hoping it works. You have to understand what each and every line of the program does.

    First, let's assume that your struct is correct. You are holding only prices, which is fine.
    Now, inside main, the first thing you want to do is create an array of MAXITEMS items named itemlist. Is that what you did? It's close, but not quite.

    Then, you want to open the myfile2.txt file in an ifstream named mystream. Ok, that looks fine. Your check to make sure the file opened looks fine, too, although I agree that you should return from main there is the file failed to open.

    Ok, now that you have created your item array and opened the file, the next step is to start reading from the file. Since only prices are in this new file, you want to read a value into the price member of each item in your array from the mystream file stream.

    Your first line of code reads from mystream into the itemlist array, but what does that mean? You can't just read into the array itself like that, you want to read into each item and read into the specific member of each item.

    Your for loop tries to do that. You loop over each item in the array and try to read into the price member. That's good. But what are you reading from? In your code, you're reading from cout? Is that where you should be getting the data? If you're trying to output to cout, then you've got the >> backwards, it should be <<. But then you still need to populate the price member variables for each item from the file.

  8. #8
    Registered User
    Join Date
    Aug 2007
    Location
    U.K.
    Posts
    148
    I have managed to read the first line from the text file into the struct:-

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    struct items
    {
    	char itemname[10];
    	double price;
    	bool luxury;
    };
    
    int main()
    {
    	items structname;
    	char arrayname[10];
    	ifstream myfile("myfile2.txt");
    
    	if(!myfile)
    	{
    		cout << "phail " << endl;
    	}
    
    	myfile >> structname.itemname;
    	myfile >> structname.price;
    	myfile >> structname.luxury;
    
    
    	myfile.close();
    	system ("pause");
    	return 0;
    }
    but I have to create "an array of structs" for /all/ the items.

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    You've got all the pieces in the various part s of code you've posted, you just have to put them together correctly.

    You were able to declare an array of items earlier in this thread. Find that code and add it to the beginning of main().

  10. #10
    Registered User
    Join Date
    Aug 2007
    Location
    U.K.
    Posts
    148
    Thanks Daved

    I got some help off digitalpoint and now am able to go through the code to see where I was going wrong. I've added the comments myself and hope they are correct.

    Code:
    
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    const int MAXCHARS = 20;
    const int MAXITEMS = 10;
    
    struct Items
    {
        char ItemName[MAXCHARS];
        double Price;
        int Luxury;
    };
    
    int main()
    {
        Items item[MAXITEMS];//creat an array called 'item' from the struct 'Items' of size 10. 
        ifstream in_stream;// open a stream (ifstream) and call it 'in_stream'.
        in_stream.open("myfile2.txt"); // open and associate the txt file 'myfile2' with the stream 'in_stream'
        if(in_stream.fail())//checks the file could be opened.
        {
            cout << "Input file opening failed.\n" << endl;
        }
       
        for(int i = 0; i<MAXITEMS; i++)//loop 10 times
        {
            in_stream >> item[i].ItemName >> item[i].Price >> item[i].Luxury;//use the stream to >> into some newly declared arrays
        }
    
        in_stream.close();//close the stream
    
        // Print out the new arrays
        for(int i = 0; i<MAXITEMS; i++)
        {
            cout << item[i].ItemName << " " << item[i].Price << " " << item[i].Luxury << endl;
        }
    
        system ("pause");
    
        return 0;
    This is a big relief, and can at last spend some time looking back at where I was going wrong and finally learn how this is all exactly done.

    Again, many thanks for showing such patience, I thought I was going to crack up at some points.
    Last edited by Swerve; 03-18-2008 at 06:13 PM.

  11. #11
    coder
    Join Date
    Feb 2008
    Posts
    127
    well Swerve, I'm glad you've reached the solution finally.
    But there is still one important thing you are missing:
    Code:
        if(in_stream.fail())//checks the file could be opened.
        {
            cout << "Input file opening failed.\n" << endl;
        }
    It's true, in_stream.fail () checks wether the file could be opened.
    But, imagine, what would happen if the file doesn't exist?
    Your program prints "Input file opening failed." and then it normally continues trying to read from a file which doesn't exist, so the program will simply crash in that case.
    This could be definitely called a BUG, and it have to be fixed some way.

    NOTE: At point 3 in my first post I'd already told you that, but probably you didn't pay enough attention. To say the truth, you didn't pay attention to the great part of my post, which contains the whole solution of your first problem.
    So, you ask for help when you're not going to take it?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Updating in a sequential file?
    By Ronnyv1 in forum C Programming
    Replies: 1
    Last Post: 03-24-2009, 04:41 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Replies: 6
    Last Post: 05-12-2005, 03:39 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

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