Thread: VOID loops

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    27

    VOID loops

    I've got a problem and I'm wondering can this be done.

    I've written a program that has a menu list and one of the options is to quit and save. the save option is contained in a VOID and the menu part is in the main.

    When you select the quit option, the save part comes up and asks for a filename. Once the filename is entered, I've got a wish to continue option. When the user selects Yes, it will continue to save, when No, I want it to go back to the menu (basically go back to the main code), not just ask for the filename again.

    Here's a cut down version of my current code, I've not got the menu void put in because it didn't work.

    Code:
    // SAVE STOCK DETAILS TO A TEXT FILE
    void save_items( int numitems)
    {
            //char filename [12];
            cout << "\nPlease enter the desired save name: ";                     
             cin >> filename;
    	
    	cout << "\n\t\tSaving as " << filename <<  " with " << numitems-1
    << " items\n\n" << "Do you wish to continue (Y/N)? ";
        cin >> ans;
        
        int i = 1;
        FILE *out_file;
            do {
                  switch (tolower(ans[0])){                     
                         
               case 'n':
                    save_items(numitems);
                    break;                
                                    
               case 'y':
              	    cout << "\n\n\tSaving as " << filename << ".......";
                   	out_file=fopen(filename,"w");
                    	do
                    	{
                      		fprintf(out_file,"%7d %25s %25s %7d %7.2f \n", slist[i].stocknumber,
                        	slist[i].description,   slist[i].supplier, slist[i].quantity,
                        	slist[i].price);
                        	i++;
    	                 }
                     while (i <= numitems-1);
    
                     cout <<"\n\n\tSaved a total of " << i-1 << " items\n\n\n";
                     fclose (out_file);
                     break;
                     }
                 } while (tolower(ans[0])!='n');        
          }
    
    
    int main(int argc, char* argv[])
    {
    	char choice[80];
    	int numitems=0;
            char searchchoice[80];
            int i;
    	
    	do {
    		system("cls");
    		cout << "\n\t\t ======MENU======\n";
    		cout << "\t\t 1.  Search for an Item\n";
    		cout << "\t\t Q.  To quit program\n";
    		cout << "\n\t\t ================\n";
    		cout << "\n\t\t Press appropriate key to select > ";
    		cin >> choice;
    
    		else if (!strcmp(choice, "1"))
                        {
                         do{       
                            system("cls");
    		                cout << "\n\t\t ======SEARCH \n";
    		                cout << "\t\t 1.  Search by stocknumber\n";
    		                cout << "\t\t Q.  End Search\n";
    		                cout << "\n Press appropriate key to select > ";
                                    cin >> searchchoice;
    		     
    		                     if (!strcmp(searchchoice, "1"))
    			                 {detailitem(numitems);
    					    waitforkey();
    		    			            }
                                         else if (!strcmp(searchchoice, "q"))
                                                   {cout <<("\n\n\t\t SEARCH ENDED\n");
    				                 cout <<("\n\t\t Returning to main menu.\n");
                                                    waitforkey();
    						            }
                                         else if (!strcmp(searchchoice, "Q"))
                                                   {cout <<("\n\n\t\t SEARCH ENDED\n");
    				                 cout <<("\n\t\t Returning to main menu.\n");
                                                     waitforkey();
    						            }
                                         else {cout <<("\t\t PLEASE TRY AGAIN\n");
    				               waitforkey();
    						            }
                                           }
                                     while (tolower(searchchoice[0]) != 'q' );
                                  } 
                            	        
                            		
    			else if (!strcmp(choice, "q"))
                        {
    			cout <<("\t\t QUIT PROGRAM\n");
    			save_items( numitems);
    			cout <<("\t\t PROGRAM COMPLETED");
    						waitforkey();
    						}
    						
    			else if (!strcmp(choice, "Q"))
                        {
    			cout <<("\t\t QUIT PROGRAM\n");
    			save_items( numitems);
    			cout <<("\t\t PROGRAM COMPLETED");
    						waitforkey();
    						}
    						
    			else    {
    						cout <<("\t\t PLEASE TRY AGAIN\n");
    						waitforkey();
    						}
      }
          while (tolower(choice[0]) != 'q');	      
          return 0;
                   }
    I included the main part of my code to help get it into context. The code currently just reruns the save_items part when No is selected and asks for a filename again. How would I get that to run the main part again?

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    >> FILE *out_file;

    That's C file io ... C++ IO (I find), is much easier ... Here's an example:

    Code:
    ofstream out_to_file ("C:\\MyFile.txt");
    while ( Parameters )
    {
    	out_to_file << MyInfo;
    }
    You can use it just like cout. To use a cin kind of file io, just call the ofstream an ifstream.

    >>if (!strcmp(searchchoice, "1"))
    couldn't you just make searchchoice a single character, and then say:

    Code:
    if ( searchchoice == 1 ) 
    {
    	// Etc.
    }

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    27
    That makes my search function a little easier to understand at first glance, so I'll probably use that, thanks.

    My problem still exists though,

    Code:
               case 'n':
                    save_items(numitems);
                    break;
    only runs the save_items void again, how would I change that so it goes back to the main?

  4. #4
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    What do you want it to do? When n is pressed, you want it to quit out of the save function?

    I'd just do:

    Code:
    bool KeepInLoop = true
    while ( KeepInLoop )
    {
        switch ( tolower(ans) )
        {
        case 'y':
            // Save stuff
            break;
    
        case 'n'
            KeepInLoop = false;
            break;
    
        default:
            cout<< endl << "ERROR IN USER INPUT ... ";
            break;
        }
    }
    or something like that. Also, sorry buddy, but your code is nasty, asthetically. It makes code MUCH easier to read if it's indented nicely, and loop braces start and end on different lines, but the same indent. Know what I mean?
    Last edited by twomers; 05-19-2006 at 02:05 AM.

  5. #5
    Registered User
    Join Date
    May 2006
    Posts
    27
    sorry if I'm being slow here but I'm not 100% sure I understand that. C++ is still a step up from what I'm used to. What I've done so far is put your bool in my do loop before the switch statement.

    Code:
        int i = 1;
        FILE *out_file;
             do{
                  bool KeepInLoop = true;
                  while ( KeepInLoop ){
                  switch (tolower(ans[0])){                     
                         
               case 'n':
                    KeepInLoop = false;
                    break;                
                                    
               case 'y':
              	    //save stuff
                 }    
          }while (tolower(ans[0])!='y'); 
    }
    I put another { before the (tolower(ans...) bit to end the new while loop, but it still doesn't work. When I go to save items, it seems the new while loop never ends and it just saves repeatedly until I close it or it crashes. And when I go to no, it just ends and it doesn't go back to main, it just does nothing.

  6. #6
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Quote Originally Posted by akira181
    sorry if I'm being slow here but I'm not 100% sure I understand that. C++ is still a step up from what I'm used to. What I've done so far is put your bool in my do loop before the switch statement.

    Code:
        int i = 1;
        FILE *out_file;
             do{
                  bool KeepInLoop = true;
                  while ( KeepInLoop ){
                  switch (tolower(ans[0])){                     
                         
               case 'n':
                    KeepInLoop = false;
                    break;                
                                    
               case 'y':
              	    //save stuff
                 }    
          }while (tolower(ans[0])!='y'); 
    }
    I put another { before the (tolower(ans...) bit to end the new while loop, but it still doesn't work. When I go to save items, it seems the new while loop never ends and it just saves repeatedly until I close it or it crashes. And when I go to no, it just ends and it doesn't go back to main, it just does nothing.
    Change the tolower(ans[0])!='y') to

    KeepInLoop == true

    in the parameters in the while loop.

  7. #7
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Hang on.

    Code:
    	bool KeepInLoop = true;
    	int i = 1;
    	while ( KeepInLoop )
    	{ 
    		cin << ans;
    		switch (tolower(ans))
    		{                     
                         
              	case 'n':
                    	KeepInLoop = false;
                    	break;                
                                    
               	case 'y':
              	    	//Put your code here to save stuff. 
    			break;
                 	}    
          	}
    That does it for you. The variable KeepInLoop is either a 1 or a 0 (true or false). The parameters in a while loop should either equal one or a zero, true or false. Ie: your tolower(ans[0])!='y' will either be true or false, there's no other way around it. So, in the while loop, or the do while loop, or whatever one you want to use, the KeepInLoop thing is initially true. A while loop, with a true parameter will go on forever, ie:

    Code:
    while ( true ) 
    {
    	// code goes on for an indefined length of time
    }
    and this will never compile.

    Code:
    while ( false) 
    {
    	// code never gets executed. 
    }
    But, if you have a while loop, and the parameters change, the loop will break.

    Code:
    bool myVar = 1;
    int i;
    while ( myVar == 1 )
    {
    	if ( i >= 100 ) break;
    	i++;
    }
    will break when i is greater or equal than 100.

    EDIT:

    you don't have to say 'while (myVar == true)', you can just say 'while ( myVar )', because it evaluates to 1 anyways.
    Last edited by twomers; 05-19-2006 at 02:54 AM.

  8. #8
    Registered User
    Join Date
    May 2006
    Posts
    27
    this is so much more confusing than programing in basic lol. this is what I've done so far
    Code:
            do {
                bool KeepInLoop = true;
                while ( KeepInLoop )
                {
                  switch (tolower(ans[0])){                     
                         
               case 'n':
                    KeepInLoop = false;;
                    break;                
                                    
               case 'y':
              	    \\save stuff
                     
               default:
                       cout <<"\n\n Please try again.";
                       waitforkey();
                       break;      
                       }
                 }while (KeepInLoop == true);         
          }
    
    int main(int argc, char* argv[])
         etc....
    When I go to compile it, it says while expected before main, but when I move the while function down a curly bracket, it says KeepInLoop undefined

    *EDIT* you beat me mid post lol. I don't get that last bit of code you put in. I understand what it means and stuff but I'm not too sure where I'm supposed to put it in my code. I'll give it a try and keep you updated

  9. #9
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Ok so. Think about it this way. You have a function, and you want the user to have a choice on whether they want to save the info, or not, right? Wouldn't it make more sense to do it this way:

    Code:
    #include <iostream>
    using namespace std;
    
    void SaveDetails( int Num )
    {
    	char ToSaveOrNotToSave;
    	bool StayInLoop = true; // This could also be an int, it doesn't matter. True
    				// is the equivalent of 1, so while( Value ), when Value
    				// is one will go on forever, and when the value of Value
    				// changes to zero, it will quit. 
    
    	while ( StayInLoop == true )	// StayInLoop is initially true, so until it is changed, the loop will stay as is. 
    	{
    		cout<< endl << "Do you want to save your details? (Y, N)";
    		cin >> ToSaveOrNotToSave;
    		
    		switch ( tolower( ToSaveOrNotToSave ) )
    		{
    		case 'y': 
    			// Now you can use your code to save the details. I left it out to save space. 
    			break;
    
    		case 'n':
    			StayInLoop = false;	// Now, when the user inputs 'n', the parameter for the loop
    						// is now 0, so when it goes back to the looping stage, it 
    						// should exit the loop.
    			break;
    
    		default:
    			cout<< endl << "Error in choice input!";
    			break;
    		}
    	}
    }
    
    int main()
    {
    	// Your stuff. 
    	SaveDetails( 2 );
    	return 0;
    }
    Just a thought.

    EDIT: Just compile that code, it works. Then look at it, try to change a couple of things around, see if you understand it. If you understand it, then try to apply your code to it. If you don't understand it, just ask me about it, and I'll explain it to you.
    Last edited by twomers; 05-19-2006 at 05:57 AM.

  10. #10
    Registered User
    Join Date
    May 2006
    Posts
    27
    hi again. This is what I've done so far, its close to working. The loop is just not ending.

    This is what I've done:
    Code:
    // SAVE STOCK DETAILS TO A TEXT FILE
    void save_items( int numitems)
    {    
       bool stayinloop = true;     
            
            cout << "\nPlease enter the desired save name: ";                     
             cin >> filename;     //char filename [12];
    	
    	while (stayinloop == true)
    	{
    	  cout << "\n\t\tSaving as " << filename <<  " with " << numitems-1
          << " items\n\n" << "Do you wish to continue (Y/N)? ";
          cin >> ans;
          int i = 1;
          FILE *out_file;
        
          switch (tolower(ans[0]))
          {                                           
               case 'y':
              	    //save stuff                 
                       break;
               
               case 'n':
                    stayinloop = false;
                    break;
                     
               default:
                       cout <<"\n\n Please try again.";
                       waitforkey();
                       break;      
                       }
                 }          
          }
    
    int main(int argc, char* argv[])
    When I select no, the program returns to the menu which is excellent. Problem now is that when I select yes, the loop doesn't end. It saves the file and starts the loop again. I've tried various ways to end the while loop but so far all I have tried has made it worse.

  11. #11
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Ok, what you have to do is this:

    save the info, and then set the StayInLoop variable to false. That will exit the loop

  12. #12
    Registered User
    Join Date
    May 2006
    Posts
    27
    cheers, got it working now thanks.

  13. #13
    Registered User
    Join Date
    May 2006
    Posts
    27
    ahhhhh, this problem has come back to haunt me again. The program is not closing now. It seems the main do loop is lasting forever. here's what I've got:

    Code:
    int main(int argc, char* argv[])
    {
    	int choice;
    	int numitems=0;
    
    	numitems = load_items( );
    	listitems(numitems);
    	waitforkey();
    
    	do {
    		cout << "\n      ======MENU======\n";
    		cout << "        1.  Add item\n";
    		cout << "        2.  Update an Item\n";
    
    		cout << "        8.  Exit without Saving Changes\n";
    		cout << "        9.  Save changes and Exit\n";
    		cout << "        ================\n";
    		cout << "        Press appropriate key to select > ";
    		cin >> choice;
    		
    		switch (choice){
    		
    			case 1: //case 1 stuff
    
    			case 2: //case 2 stuff
                            		
    			case 8:
    				cout <<("\n\t\t PROGRAM NOT SAVED\n");
    			        waitforkey();
    				break;
                            
                            case 9:
    				cout <<("\n\t\t SAVING CHANGES\n");
    				save_items( numitems);
    				waitforkey();
    				break;            
                			
    			default: // default stuff
      }}
          while (choice != 8 || 9);	      
          return 0;
                   }
    My save part is still the same as posted above and it does save. For some reason now that I've changed the save part, the do loop in the main doesn't end when I press 8 or 9, and it does what its supposed to (i.e. it either does nothing or it saves) but it then flashes the menu up again instead of closing.

    I can put return 0 inside the cases to end the program but this isn't the proper way to do it. I'm pretty sure what I've got in the while function is correct but I've tried changing it as well but to no avail. Why is this?
    Last edited by akira181; 05-21-2006 at 01:20 PM.

  14. #14
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    don't know if this is the only problem with it, but

    while (choice != 8 || 9);

    doesn't work - should be:

    while (choice != 8 || choice != 9);
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  15. #15
    Registered User
    Join Date
    May 2006
    Posts
    27
    even when I change it to while (choice != 8 || choice != 9); both options do not close the program. Here's what I've done in my save loop, cause it is slightly different from before.

    Code:
    // SAVE STOCK DETAILS TO A TEXT FILE
    void save_items( int numitems)
    {    
            bool stayinloop = true;     
            
            cout << "\nPlease enter the desired save name: ";                     
            cin >> filename;     //char filename [12];
    	
    	while (stayinloop == true)
    	{
    	  cout << "\n\t\tSaving as " << filename <<  " with " << numitems-1
               << " items\n\n" << "Do you wish to continue (Y/N)? ";
               cin >> ans;
               int i = 1;
               FILE *out_file;
        
          switch (tolower(ans[0]))
          {                                           
               case 'y':
                     //save stuff
                     stayinloop = false;
                     break;
               
               case 'n':
                    stayinloop = false;
                    break;
                     
               default: //default stuff
                       }
                 }          
          }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to better manage large .cpp files
    By 39ster in forum C++ Programming
    Replies: 6
    Last Post: 08-25-2008, 08:24 AM
  2. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  3. Error, not sure what it means.
    By RealityFusion in forum C++ Programming
    Replies: 1
    Last Post: 09-25-2005, 01:17 PM
  4. Can't Find Conio.h?
    By drdroid in forum C++ Programming
    Replies: 27
    Last Post: 09-26-2002, 04:24 AM
  5. Just one Question?
    By Irish-Slasher in forum C++ Programming
    Replies: 6
    Last Post: 02-12-2002, 10:19 AM