Thread: reading text file to struct help needed!

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    33

    Smile reading text file to struct help needed!

    Hi,

    I am having trouble where to begin reading in my text file my little program I created.
    below is the text file i want to read into a struct in my program.

    I just want some help on parsing the file. whats the best way to do it?

    I could read each line into a string, search for a ':' and then read the file into my struct, but that seems a little tedious to me. surely there is a better way. Just some hints and tips to put me in the right direction. I am trying to use only c++ but yeah I now a struct is from C. Not ready for classes just yet.

    I don't want someone to write the code for me please!(at least not yet!)


    the file.....
    Code:
    Name	: John
    Race	: Human
    Class	: Fighter
    Strength	: 18
    Intelligence	: 10
    Dexterity	: 14
    Wisdom	        : 8
    Charisma	: 18
    Luck	        : 10
    my struct.....

    Code:
    struct character
    {
    	string name;
    	string namerace;
    	string nametype;
    	int str;
    	int dex;
    	int cha;
    	int wis;
    	int luk;
    	int inte;
    }
    werdy666!

  2. #2
    a newbie :p
    Join Date
    Aug 2008
    Location
    Zurich, Switzerland, Switzerland
    Posts
    91
    I could read each line into a string, search for a ':' and then read the file into my struct, but that seems a little tedious to me
    Don't you think that's the way it should be...
    find position of ':'
    trim form 0 to pos-1 and trim from pos+1 to maxlength
    remove spaces
    put in to a map, why? so that parsing will be done once...

    http://www.adp-gmbh.ch/cpp/config_file.html

  3. #3
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    If you can stand having constant size strings then I would use char arrays for your text. This will allow you to read the entire struct in with no parsing.
    Otherwise you will have to create a readString and a writeString function to read/write STL strings from disk.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. Poblem reading struct in a file
    By The_Kingpin in forum C Programming
    Replies: 1
    Last Post: 10-24-2004, 07:02 PM