Thread: Help with Do While loop

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    11

    Help with Do While loop

    I'm very new at this and this is my first attempt at writting a real program. My program is simple. It's supposed to take a question you input and write it to a text file for later use. Here is my code:

    Code:
    #include <iostream>
    #include <fstream>
    
    
    using namespace std;
    
    main ()
    {
        char question[200];
        int x;
        
            
            do
            {
            cout<<"Enter a question:\n\n";
            cin>>question[200];
            ofstream a_file("test.txt",ios::app);
            a_file<<question[200]<<"\n";
            cout<<"Would you like to enter another question?\n";
            cout<<"1 for yes. 2 for no: ";
            cin>>x;
            }
            while (x!=2);
                
        cout<<"Your submition has been saved. Have a nice day!\n";
        cout<<"Press enter to close the program.";
        cin.get();
        
    }

    When you input your question and hit enter, it asks you if you want to input another question. 1 for yes 2 for no. If you hit 1, it should loop back to the beginning. If you hit 2, it should break from the loop and display a message saying your input was saved. The problem is when I enter a question like "what color is the sky?", sometimes it will go into an infinite loop. Other times it will loop 2 or 3 times and it does not break the loop when I hit 2. I just don't understand that different effects I'm getting as a run the program over and over. I'm really lost here, please help me out. Thanks.

  2. #2
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    463
    take " ofstream a_file("test.txt",ios::app);" outside the loop. you only need to open a file once. Remember to close it with a_file.closed();

    Code:
    question[200]
    you're trying to access the 201st character, not the entire character string. So , you must take out the [200] in the do-while loop.
    "All that we see or seem
    Is but a dream within a dream." - Poe

  3. #3
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Thanks nimitz. I had a_file.close() there before but i removed it because I kept getting an error but once I removed ofstream a_file("test.txt",ios::app) from the loop, the error went away. I also removed the 200 from the loop but I'm still getting an ifinite loop. The weird thing is that it loops infinitely depending on what I put in. If just type gibberish like "dalsjfdsakfj" it goes to the next command but will not execute instruction outside of the loop when I hit "2". If I input an actual question like "how are you?" then it loops infinitely. I don't understand...

    Code:
    #include <iostream>
    #include <fstream>
    
    
    using namespace std;
    
    main ()
    {
        char question[200];
        int x;
            
        ofstream a_file("test.txt",ios::app);
            do
            {
                cout<<"Enter a question:\n\n";
                cin>>question;
                a_file<<question<<"\n";
                cout<<"Would you like to enter another question?\n";
                cout<<"1 for yes. 2 for no: ";
                cin>>x;
            }
            while (x!=2);
    
        a_file.close();
        cout<<"Your submition has been saved. Have a nice day!\n";
        cout<<"Press enter to close the program.";
        cin.get();
        
    }

  4. #4
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Now thats intereting! After doing some research, I learned that the cin command only accepts inputs up to a space. Anything after the space gets stored in memory and is automatically applied to the next cin. This is why the program kept looping when I entered something with spaces in it. I solved the problem by using cin.getline along with cin.clear and cin.ignore.

    Code:
    #include <iostream>
    #include <fstream>
    #include <limits>
    
    using namespace std;
    
    main ()
    {
        char question[200];
        int x;
        
        
        ofstream a_file("test.txt",ios::app);
            do
            {
                cout<<"Enter a question:\n\n";
                std::cin.getline(question,200);
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                a_file<<question<<"\n";
                cout<<"Would you like to enter another question?\n";
                cout<<"1 for yes. 2 for no: ";
                cin>>x;
            }
            while (x!=2);
        a_file.close();
        cout<<"Your submition has been saved. Have a nice day!\n";
        cout<<"Press enter to close the program.";
        cin.get();
        
    }
    But there is still the problem of the code outside the loop not executing when the loop is terminated. I'll keep looking and post the answer here for anyone else who needs it.

  5. #5
    Registered User
    Join Date
    Mar 2013
    Location
    Portugal, Porto.
    Posts
    105
    I assume you're using some kind of "Learn C++ in 1 week" book, considering no one starts out using cicles and files in his/her first program. Learn your priorities first. Start with the simple.

  6. #6
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    This is not my first program. Thanks for your input.
    Last edited by darkc0de; 04-05-2013 at 04:12 AM.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Change your question from using a char array to std::string. Use std::getline to read string instead of std::cin.getline. No need to use std::cin.ignore when using std::getline. Files never need to be closed explicitly. They close automatically when they go out of scope, so no call to close() needed.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Thanks for you inputs. I'll give that a try but can you think of a reason why that code after the loop would not run when the loop is closed? I've been racking my brian on this. Eveything I've learned about C states that when a loop finishes, the code after the loop is run. Instead the program just closes. I can't figure why the code is not running.

  9. #9
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Hmmm. So after I ran it with g++, it works fine. I wonder why it doesn't work with my IDE. It must be a problem with my IDE.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Perhaps the problem is that you think it doesn't run the code, but it really does.
    See SourceForge.net: Pause console - cpwiki.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Jun 2012
    Location
    Morden, UK
    Posts
    128
    I actually Khabz had a good point earlier, although maybe it came across as a bit sharp! I'm new to this as well and I'm not at writing to text files yet even after hours and hours and studying loops/functions and basic stuff.

    Code:
    while (x!=2);
    This seems unnecessary to me. As I said, I'm new to this as well, but your instructions says "Press 1 to enter another question". With this condition, I could press anything that is not a '2'. Why not:

    Code:
    while (x==1);
    i.e. "Press 1 to enter another question"

    And this bit:

    Code:
    std::cin.getline(question,200);
    My beginners learning (thanks to Alex and his book!) tells me to use:

    When you read in strings, sometimes you want to read a whole line at a time. There is a special function, getline, which can be used to read in the whole line. It will even automatically discard the newline character at the end.

    To use getline, you pass in a source of input, in this case cin, the string to read into, and a character on which to terminate input. For example, the following code reads the user's first name:

    getline( cin, user_first_name, '\n' );


    - Alex Allain, Jumping into C++
    And do you even need to put std:: in front of cin? Namespace std is being used so I'm not sure you need to. There's no std:: in front of cout in your code.

    Anyway, I can't really help much further as I don't even know what [200] does! Looking at others' code certainly helps me though. I'm sure the experts here can offer much more than myself, but I'm working on that
    Last edited by samwillc; 04-05-2013 at 12:14 PM.

  12. #12
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    good things there, nice one. In response to your later query - using namespaces is not always preferred, there has been quite a bit of discussion on that you can find on these pages. But declaring the namespace and then using that scope operator gives compiler warnings, i say that but i was unable to replicate one i got recently for just that reason, writing into an old file i forgot it was there... maybe thats part of the problem with them..
    Last edited by rogster001; 04-05-2013 at 01:39 PM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  13. #13
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Hey thanks for your reply sam. I've been studying and praticing C++ for over a month now and written over 20 programs prior to this. I started off with "Hello world" just like everyone else and gradually worked my way up to this. I have used every component of this program in other simpler examples but there comes a time where you have to move up to the more difficult things. Really, considering how in-depth C++ is, this program is extremely simple and a good first project. I'm bound to run into trouble but thats part of learning. Challenging yourself and asking for help when you are stumped. Thats just some advice from one beginner to another. Learn the basics first but don't be afraid to apply what you learned to real world projects early on. It will motivate you. Oh and Writing to text files is not difficult. Its easier than loops and functions. It was actually the easiest part of this whole program.

    As for your inputs? Yes I realized that std was not necessary and removed it.

    The the while statement was set that way it because I want to limit the user to only two possible inputs. I'm working on code that will produce an error message if the wrong input is detected. What I wanted to to first was start simple and get the program working and then add these things later.

    I tried to use getline() but i got an error message but a few people have suggested it so I will retry it. Good luck in your studies.
    Last edited by darkc0de; 04-05-2013 at 08:18 PM.

  14. #14
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Quote Originally Posted by Elysia View Post
    Perhaps the problem is that you think it doesn't run the code, but it really does.
    See SourceForge.net: Pause console - cpwiki.
    I don't know if that was a hint on your part but you were right. The code was running. The problem was a value was being passed to the cin.get() which caused the program to terminate. I fixed the problem by inserting a second cin.get() under the first one. That kept the program running long enough for me to see the closing message. Here is my new code:

    Code:
    #include <iostream>
    #include <fstream>
    #include <limits>
    #include <string>
    
    using namespace std;
    
    int main ()
    {
        string question;
        int x;
        
        
        ofstream a_file("test.txt",ios::app);
            do
            {
                cout<<"Enter a question:\n\n";
                getline(cin,question);
                a_file<<question<<"\n";
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout<<"Would you like to enter another question?\n";
                cout<<"1 for yes. 2 for no: ";
                cin>>x;
                
            }
            while (x!=2);
            
        a_file.close();
        cout<<"\nYour submition has been saved. Have a nice day!\n";
        cout<<"Press enter to close the program.";
        cin.get();
        cin.get();
        
    }
    Everything is solved now thanks guys for your help.
    Last edited by darkc0de; 04-05-2013 at 10:51 PM.

  15. #15
    Registered User
    Join Date
    Jun 2012
    Location
    Morden, UK
    Posts
    128
    Code:
    ofstream a_file("test.txt",ios::app);
    I have a few questions about this if you (or anyone else) wouldn't mind indulging me:

    1) Where on your computer is the file "test.txt"? Could this be written as a path? i.e. "/Users/Sam/Documents/test.txt"
    2) If this file does not exist, is it created?
    3) If it does exist, is the question appended to the end of the text in the file or is the file re-created? i.e. do earlier questions persist within the file or not

    Thanks for any extra info.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loop stops working when loop >45 ??
    By Zul56 in forum C Programming
    Replies: 3
    Last Post: 12-11-2012, 03:40 PM
  2. Help - Collect data from Switch loop inside While loop
    By James King in forum C Programming
    Replies: 15
    Last Post: 12-02-2012, 10:17 AM
  3. Replies: 1
    Last Post: 12-26-2011, 07:36 PM
  4. Replies: 23
    Last Post: 04-05-2011, 03:40 PM
  5. for loop ignoring scanf inside loop
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-17-2007, 01:46 AM