Thread: getine command skipping help!!!

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    10

    getine command skipping help!!!

    I'm using getline to receive some characters but it skips out on receiving some of the data. In detail the program skips out asking for the course code the 1st time.
    Here is the code:

    Code:
    // This function is to be used to get the courses completed at the end of each semester and save the information to a file (includes course code, course name, letter grade.
    
    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main()
    
    {
      ofstream myfile;
    
      int numCourse;
      char courseCode[20];
      char courseName[20];
      char letterGrade[5];
    
       myfile.open ("completed.txt");
    
       cout<<"How many courses have you done this semester?"<<endl;
       cin>>numCourse;
    
       for(int i=0;i < numCourse;i++)
       {
         cout<<"Please enter course code"<<endl;
         cin.getline(courseCode,20);
         myfile<<courseCode[20]<<"  ";
    
    
         cout<<"Please enter course name"<<endl;
         cin.getline(courseName,20);
         myfile<<courseName[20]<<"  ";
    
         cout<<"Please enter your letter grade"<<endl;
         cin.getline(letterGrade,5);
         myfile<<letterGrade[5]<<"  \n";
    
    
       }
    
          myfile.close();
    
          return 0;
    }
    Your assistance would be greatly appreciated. Thanks in advance!!

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    cin>>numCourse;
    
       for(int i=0;i < numCourse;i++)
       {
         cout<<"Please enter course code"<<endl;
         cin.getline(courseCode,20);
    This is actually a common problem that's asked about here. The issue is that first cin line highlighted in red above. The newline character is left in the input stream by that command and the first time through the for loop, the getline call sees that newline and thinks that the user pressed the enter key which makes things look like the command was skipped. The usual solution is that whenever you start mixing straight cin >> statements with getline calls you need to call the stream's ignore member function after the cin >>.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    10
    WOW! Thanks. I never thought of that possibility. Thank you so much!

Popular pages Recent additions subscribe to a feed