Thread: File I/O?

  1. #1
    Registered User Aalmaron's Avatar
    Join Date
    Jan 2004
    Location
    In front of a monitor
    Posts
    48

    File I/O?

    ok, here's my problem. i can write to a file just great. it formats it exactaly how i want it to. the problem is that i can't read from a file. everytime i try to read from a file and i want something other than a char array, it doesn't read correctly, and with my current reading system it won't read correctly for even that. can i get a few pointers?

    i'm confident that this is where my problem is.
    Code:
     
    	char  inName[100];		// name of the food
    	int	  inCategory;		// what kind of food
    	float inCalories;		// calories
    	float inCarbohydrates;	// grams
    	float inFat;			// grams
    	float inCholesterol;	// grams
    	float inSodium;			// grams
    	float inProtein;		// grams
    	ifstream in("data.txt");
    	counter = 0;
    	while(in.peek() != EOF)
    	{
    		in.getline(inName, 100, '~');
    		inCategory = (int)in.get();
    		inCalories = (float)in.get();
    		inCarbohydrates = (float)in.get();
    		inFat = (float)in.get();
    		inCholesterol = (float)in.get();
    		inSodium = (float)in.get();
    		inProtein = (float)in.get();
    
    		data[counter].setname(inName);
    		data[counter].setcategory(Category(inCategory));
    		data[counter].setcalories(inCalories);
    		data[counter].setcarbohydrates(inCarbohydrates);
    		data[counter].setfat(inFat);
    		data[counter].setcholesterol(inCholesterol);
    		data[counter].setsodium(inSodium);
    		data[counter].setprotein(inProtein);
    
    		counter++;
    	}
    	in.close();
    but i don't know what i need to change.

    this is what is in data.txt
    Multi grain bread~6 90 16 0 .5 .125 4
    the goal is to get it to read until the tild, and made that the name, then read the next number, make that the food group, red next number, make that the calories, etc etc.

    thanks for taking the time to view my thread

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    My choice would be getline to read the whole line, then sscanf to parse the line.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    get with no parameters takes a byte outta the file and stores it in your variables, which is not what you want. Your input method in general needs to be more refined. Given the way you like to do things, for you I suggest a combination of getline and stringstream, or strtol().

  4. #4
    Registered User
    Join Date
    May 2006
    Location
    Berkshire, UK
    Posts
    29
    How about using the >> opertor? You could even go as far as to creat your own extractors if you have any odd data types (not that you do - they are all floats and a string).

    If that is too complicated then read the whole lof (line by line) into a string and use the string manipulation functions to sort it all out. I mean the C++ std::string, rather than char{100]. They are very powerful and really easy to use. You can, for example, set the delimiter (tilde for your first string) vey simply:
    Code:
    while(in)
    {	in.getline(cbuf,MAX_BUF_SIZE); //Whole line
    	string sbuf(cbuf);
    	if(sbuf.empty())
    		continue; //Blank line, nothing to do...
    	//Get inCaegory (~ terminated)
    	int ind=sbuf.find_first_of("~");
    	inCategory=sbuf.substr(0,ind);
    	...
    }
    Hope that helps.
    Last edited by michaels-r; 05-24-2006 at 01:23 PM.

  5. #5
    Registered User Aalmaron's Avatar
    Join Date
    Jan 2004
    Location
    In front of a monitor
    Posts
    48
    wow, awesome, thats a lot of help you guys rock. i'm not allowed to use any strings in this program, so i have to use char arrays though :-/

    i couldn't figure stringstream or strtol, so i decided to go with sscanf, which is working great. for the first time its actualy reading from a file corectly.

    it's 100% working now.

    this is what it looks like now.
    Code:
     
    		char  inAll[100];		// the data as retrieved from file.
    		char  inName[100];		// name of the food
    		int	  inCategory;		// what kind of food
    		float inCalories;		// calories
    		float inCarbohydrates;	// grams
    		float inFat;			// grams
    		float inCholesterol;	// grams
    		float inSodium;			// grams
    		float inProtein;		// grams
    		ifstream in("data.txt");
    		counter = 0;
    		while(in.peek() != EOF)
    		{
    			in.getline(inName, 100, '~');
    			in.getline(inAll, 100, '\n');
    			sscanf( inAll, "%d %f %f %f %f %f %f", &inCategory, &inCalories, &inCarbohydrates, &inFat, &inCholesterol, &inSodium, &inProtein);
    
    			data[counter].setname(inName);
    			data[counter].setcategory(Category(inCategory));
    			data[counter].setcalories(inCalories);
    			data[counter].setcarbohydrates(inCarbohydrates);
    			data[counter].setfat(inFat);
    			data[counter].setcholesterol(inCholesterol);
    			data[counter].setsodium(inSodium);
    			data[counter].setprotein(inProtein);
    			// i figure that 30 will be enough.
    			
    			counter++;
    		}
    		counter--;
    		counter--;
    		in.close();
    	}
    dunno why i had to have 2 "counter--"'s, but everything works great now thanks again guys!

  6. #6
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005

    Thumbs up

    My sscanf version went something like this.
    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdio>
    using namespace std;
    
    int main()
    {
       char  line[100];        // name of the food
       char  name[100];        // name of the food
       int   inCategory;       // what kind of food
       float inCalories;       // calories
       float inCarbohydrates;  // grams
       float inFat;            // grams
       float inCholesterol;    // grams
       float inSodium;         // grams
       float inProtein;        // grams
       ifstream in("file.txt");
       while ( in.getline(line, sizeof line) )
       {
          if ( sscanf(line, "%99[^~]~%d %f %f %f %f %f %f", name,
                      &inCategory, &inCalories, &inCarbohydrates, &inFat,
                      &inCholesterol, &inSodium, &inProtein) == 8 )
          {
             // ...
    //       ++counter;
          }
       }
       return 0;
    }
    If you only increment your loop counter on success, then you don't need to do any decrements.

    The stringstream version is fairly similar, and I chose to ditch char arrays for strings as well, much like citizen suggested.
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    int main()
    {
       string line;
       string name;             // name of the food
       int    inCategory;       // what kind of food
       float  inCalories;       // calories
       float  inCarbohydrates;  // grams
       float  inFat;            // grams
       float  inCholesterol;    // grams
       float  inSodium;         // grams
       float  inProtein;        // grams
       ifstream file("file.txt");
       while ( getline(file, line) )
       {
          istringstream iss(line);
          if ( getline(iss, name, '~') && 
               iss >> inCategory >> inCalories >> inCarbohydrates >> inFat
                   >> inCholesterol >> inSodium >> inProtein )
          {
             // ...
          }
       }
       return 0;
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  3. 2 questions surrounding an I/O file
    By Guti14 in forum C Programming
    Replies: 2
    Last Post: 08-30-2004, 11:21 PM
  4. File I/O problems!!! Help!!!
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 05-17-2002, 08:09 PM
  5. advice on file i/o
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-29-2001, 05:56 AM