Thread: How to read files?

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    673

    How to read files?

    Ok, I am making a character creation program to assist my cousins game he is making. I need to be able to save thigs like character name, class, race, and ect,ect to a file. And then be albe to make a code to load the information into the game. I can get it to save to a .txt file with <ofstream> but I cant figure out how to load the information I saved to the .txt. I also need to be able to figure out how to utilize .ini files to configure ingame options. I am putting the character creation code up here to show how I am saving the stuff to a file but...I deleted all attempts at accessing and loading info from the file thanks ALOT in advance.

    Code:
    /*******************************************************************************
    Ok, This is strictly here for the C Boards forum. The Only selection that works 
    is the Create Character. I dont want to write all the code a right now so I just
    made the program work not be complete. If you choose any option besides create
    character it will just loop back to the menu until you choose create character.
    Well as far as I know you are all alot smarter than me so I havent much more to
    say as far as how the program works and such it is easy to read and figure out.
    *******************************************************************************/
     
    #include <iostream>
    #include <fstream>
    	
    using namespace std;
    	
    int main()   
    { 
    	float vn;
    	int a[10];
    	int z[3];
    	vn = 1.01;
    	string races[11] = { "Troll", "Titan", "Firbolg", "High Elf", "Half-Elf", 
    					   "Dwarf", "Ogre", "Iskar", "Human", "Melerrian", "Sylph"};
    	string names[12] = { "Raigne", "Centrea", "Valos", "Sathias", "Maria", "Sarah",
    					   "Gonalas", "Sentrus", "Darivas", "Verinias", "Burlon", "Garlonsus",};
    	cout << "*******************************************************************\n";
    	cout << "*		   Xinathian Character Creator V " << vn << "b!!!				*\n";
    	cout << "*******************************************************************\n";
    	do {
    		if ( z[1] == 1 ) { system("cls"); }
    	cout << "***********************\n";
    	cout << "*(1) Create Character *   Make A New Character\n";
    	cout << "*(2) Modify Character *   Modify An Existing Character\n";
    	cout << "*(3) Options		  *   Change Options for game\n";
    	cout << "*(4) Exit			 *   Exit Program\n";
    	cout << "***********************\n";
    	cout << "Selection: ";
    	cin >> a[1];
    	switch ( a[1] ) {
    		   case 1:
    				cout << " Make A New Character? \n";
    				cout << " (1) Yes  (2) No \n";
    				cout << " Selection: \n";
    				cin >> a[2];
    				if ( a[2] == 1 ) {
    					 ofstream a_file ( "Character.ini" );
    					 cout << "Ok.. Please Select Your Race\n\n";
    					 for ( int x = 0; x < 10; ++x ) {
    						 if ( x == 7 || x == 14 || x == 21 ) {
    							  cout << "\n";
    							  }
    						 cout << x + 1 << ") " << races[x] <<" ";
    						 if ( x == 9 ) { cout << "\n\n"; }
    						 }
    					 cout << " Your Selection Please: ";
    					 cin >> a[3];
    					 cout << " You Chose "<< races[a[3] - 1] <<"\n Is this correct?!";
    					 cout << " (1) Yes (2) No";
    					 cout << " Selection: ";
    					 cin >> a[4];
    					 if ( a[4] == 1 ) {
    						  a_file << ( races[a[3] - 1] );
    						  cout << " Ok choose your character name please. \n\n";
    						  for ( int t = 0; t < 12; ++t ) {
    							  if ( t == 7 || t == 14 || t == 21 ) {
    							  cout << "\n";
    							  }
    						 cout << t + 1 << ") " << names[t] <<" ";
    						 if ( t == 11 ) { cout << "\n\n"; }
    						 }
    						 cout << "Your Selection Please: ";
    						 cin >> a[5];
    						 cin.ignore();
    						 cout << "You Chose "<< names[a[5] - 1] <<" For Your Name.";
    						 a_file <<"\n";
    						 a_file << ( names[a[4] - 1] );
    						 cin.get();
    						 return 1;
    						  }
    					 else {
    						  cout << " Ok returning to menu";
    						  z[1] = 1;
    						  }
    					 cin.get();
    					 }
    				else {
    					 cout << "Ok returning to menu";
    					 z[1] = 1;
    					 } 
    			case 2:
    				 z[1] = 1;
    				 break;
    			case 3:
    				 z[1] = 1;
    				 break;
    			case 4:
    				 return 1;
    				 break;
    			default:
    					z[1] = 1;
    					break;
    	cin.get();
    } 
    } while ( z[1] == 1 );
    cin.get();
    }
    EDIT: OK, that is the new code opposed to the EXTREMELY long one before. this should help you guys to help me ( or so I hope ). Well anyways I posted once at the bottom so you might read that before you read this. Well I hope you guys can help me Thanks Alot. Maybe someday Ill be able to returnthe favor.
    Last edited by Raigne; 11-23-2005 at 01:40 PM.

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Before I get into reading a file, I'm gonna teach you how to shorten this code by using something called an array with a meaningful index. Consider something like this:

    Code:
        string races[10] = { "Human", "Elf", "Half-elf", "Dwarf", "Goblin", 
                             "Giant", "Demon", "Iskar", "Gnome", "Orge"};
        int choice;
        
        for (int x = 0; x < 10; x++) {
            cout << x + 1 << ". " << races[x] << endl;
            }
        
        cout << "Please, select a race: ";
        cin >> choice;
        
        cout << "You picked " << races[choice - 1] << ".";
    You see how the use of the index as the value entered can simplify your code? Let this idea sink in a bit, then we'll get into file reading.
    Last edited by SlyMaelstrom; 11-22-2005 at 10:10 PM.
    Sent from my iPadŽ

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    hmmm, that shortens things ALOT. Now I have to rewrite the code though lol. Makes sense that function is used instead of IF/ELSE. It gets really old making those if else function. Well I will rewrite the code then I will edit my first post and put code in.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Quote Originally Posted by SlyMaelstrom
    Code:
        string races[10] = { "Human", "Elf", "Half-elf", "Dwarf", "Goblin", 
                             "Giant", "Demon", "Iskar", "Gnome", "Orge"};
    Dungeons & Dragons (TM)

  5. #5
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Heh, I just took the least obscure races from his code, which looks to me like an odd mix of Everquest and Magic: The Gathering.
    Sent from my iPadŽ

  6. #6
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    Your right all my races are from either Everquest, Magic:the gathering, Dark age of camelot or, D&D)
    I should Have my code completed in about about 2 hours then I post it. I am getting alot of syntax errors ( i keep missing a } or ; ) for some wierd reason lol.

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Ok, I know the code IS REALLY long
    What patience! In programming, if you find yourself typing something over and over again, you are most likely doing something wrong.

    Next, what do you think these lines do:
    Code:
    cin.ignore();
    Try commenting them out and seeing if anything executes differently.

  8. #8
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    At the cprogramming tuturials, it says (unless i read wrong wrong0 that
    Code:
     cin.ignore();
    made the program ignore the last enter that the user input. If I missunderstood that point or am just imagining it please do tell me the true meaning of it plz.
    I got kicked off my computer at around 3 am this morning (was rewriting code) so now I and still writing it should be done soon. As long as I dont get anymore large intteruptions.

    EDIT: I am writing the new code without any of the
    Code:
     cin.ignore();
    syntax in it. I made alittle program to experiment with them and I must be usinbg them wrong or sumthing because they have absolutely no effect on the program as far as I can tell. Can anyone please tell me what the
    Code:
     cin.ignore();
    does?
    Last edited by Raigne; 11-23-2005 at 10:39 AM.

  9. #9
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Yes, you're correct that cin.ignore() will remove the next character in the input buffer, but you should understand that:

    Code:
     // Input buffer: [  55\n22  ]
    
    cin >> integer1 >> integer2;  // will remove all whitespace automatically
    cout << integer1 << endl << integer2;
    Sent from my iPadŽ

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    The cin.ignore() ignores a single character in the input stream. In your original code, you had them after calls to cin >>. When the user typed input (for age or birthyear, for example), they have to hit enter to send their input to you. When they hit enter, that leaves a newline character in the cin stream. The call to cin.ignore() ignores that character, since you don't need to use it.

    In this case, it isn't necessary, because the next call to cin >> will also ignore any whitespace (i.e. spaces, tabs, newlines) in front of the data it tries to get from the user. This is probably what 7stud is referring to.

    However, I'd suggest leaving them in there after every call to cin >> just as you have it in your original post.

    The reason is that in some cases, it helps to specifically ignore that newline. If you ever want to get a name from the user that spaces in it (like a player name), you would use the getline function. The getline function won't work if there is a newline in the stream, so that call to ignore will help make it work. Another place that it helps is in your code. At the end you have a cin.get() to wait for the user to hit enter before the console window closes. However, if you remove the cin.ignore() call after the last user input, then the newline in that input will still be there, and the cin.get() will get that newline instead of waiting for the next one which means the console will close.

    In short, hopefully you understand it a little better, but in the end, your usage of cin.ignore() was fine.

  11. #11
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    Well, that helps to know, I have only been programming for maybe 2 weeks. So, I am really new to how it works. I noticed that I need either 2 of the cin.get(), in order to keep the proram from terminating automaticly at the end of program. So it is just I need to add the ignore function in to keep the program open.
    I know htis is kinda off the point of the of the thread but if I made a code like the following. (It prolly wont actually compile and work I just want to check something)
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
         int a[3];
         cout << "USELESS STING OUTPUT";
         do {
                a[1] = a[1] + 1;
                cout << "Hello";
                do {
                         a[2] = a[2] + 1;
                         cout << "Bubbles\n";
                         cout << a[2] <<endl;
                     } while ( a[2] < 11 );
            } while ( a[1] < 5 );
    }
    Ok, now for my question. Will both of those DO/WHILE function work or will only the 2nd one work. Because I am trying to be able to loop back to the menu. ( Which I can get it to work up to a certain point) but then my program just terminates without returning 1 or 0 to computer. Well thanks for the help in advance. ( I got stuck watching my baby sis so writing code is taking a little while)

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You would want to initialize a[1] and a[2] before the loops start, but assuming you did (initialize them to 0) your output would be:
    Code:
    HelloBubbles
    1
    Bubbles
    2
    Bubbles
    3
    ...
    Bubbles
    10
    Bubbles
    11
    HelloBubbles
    1
    Bubbles
    2
    ...
    Bubbles
    11
    HelloBubbles
    1
    ...
    Bubbles
    11
    HelloBubbles
    1
    ...
    Bubbles
    11
    HelloBubbles
    1
    ...
    Bubbles
    11
    5 "Hello", each with 11 "Bubbles".

  13. #13
    Registered User
    Join Date
    Nov 2005
    Posts
    673
    Ok, finally I have part of the code finished. This program WILL compile and run but BEWARE that it saves a .ini file to the directory of the .exe... Well now that I have shortened my code (ALOT ALOT) . Now can we get back to the purpose of the thread. I asked HOW TO read info from a file to load a character.

    IF YOU WANT THE NEW CODE REFER TO FIRST POST.

  14. #14
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    What does an example .ini file look like when you run through the code to save out characters? It looks like it will be like this if I choose Ogre and Maria:
    Code:
    Ogre
    Maria
    To read it in, follow the same format of how you wrote it out. First open an ifstream instead of ofstream. Then read into a variable from the ifstream. The first variable will be the race (since that is the first variable you write out). The next variable will be the name.

    Your current code looks like it only handles a single character in the ini file (it doesn't open the output file for append, and it doesn't separate the name of one character from the race of the next character). If that's what you intended, then that's fine. If you want the user to be able to choose multiple characters, you'll have to add logic to the output and input.

  15. #15
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Using your book or compiler help files to read more about I/O issues is a good idea, but this should get you going. In general, you read files either with FILE *, if you want to use C syntax, or streams, if you want to use C++ syntax. You can either use the general stream called fstream in ios::in mode or, my preference, an ifstream, which is an fstream dedicated to input only, so you don't have to indicate whether you want to input or output with the stream (you would use ofstream to write to file). Once you have declared an instance of the stream you associate a file with it (declaration and association can be done in a single statement if you wish), check that it was opened, and then use the stream as you would any other istream object, like cin. There is a variety of other flags/modes that can be used, if desired. One common one is to read/write in binary mode using the ios::binary modifier.
    You're only born perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read Only files
    By DominicTrix in forum C++ Programming
    Replies: 4
    Last Post: 12-11-2004, 02:55 AM
  2. using threads to write & read from files
    By kishorepalle in forum C Programming
    Replies: 4
    Last Post: 10-19-2004, 05:19 PM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. trying to read all asci char's in files
    By brane_sail in forum C++ Programming
    Replies: 1
    Last Post: 09-02-2002, 11:33 AM
  5. Replies: 1
    Last Post: 07-24-2002, 06:33 AM