GetLine not working

When I call out GetStudentData it jumps right to Artist, but never prompts me for Title? Is my code just bad or is this a bug.

#include <iostream>
#include <string>
#include <sstream>
#include<fstream>

using namespace std;

class Student
{
string title;
char artist[20];
int tracks;
float price;

public:
void GetStudentData();
void ShowStudentData();
};

void Student :: GetStudentData()
{
cout << "Title: ";
getline(cin, title);
cout << "Artis:";
cin >> artist;
cout << "Tracks: ";
cin >> tracks;
cout << "Price: ";
cin >> price;
}

void Student :: ShowStudentData()
{
cout << "CD Details are:" << endl;
cout << "Title: " << title << endl
<< "Artist: " << artist << endl
<< "Tracks: " << tracks << endl
<< "Price: " << price << endl;
}

char fname[100];

int main(int argc, char *argv[])
{
char ans='y';
Student sobj;

//We open student.dat in append mode
/*ofstream out("student.dat", ios::app | ios::binary);*/
cout << "Enter the Filename you want to write to: " << endl;
cin >> fname;

ofstream out(fname, ios::app | ios::binary);

if(out.is_open())
{
//Loop will continue until something other then y is entered
while( ans == 'y')
{
cout << endl << "Continue ?";
cin >> ans;
if(ans == 'y')
{
sobj.GetStudentData();
out.write((char*) & sobj, sizeof(sobj));
}
}
}
out.close();

ifstream in(fname, ios::binary);
if(in.is_open())
{
while(!in.eof())
{
in.read((char*) &sobj, sizeof(sobj));
if(!in.eof())
{
sobj.ShowStudentData();
}
}
}
in.close();



system("PAUSE");
return EXIT_SUCCESS;
}
Try putting cin.ignore(); before you ask for title. ;)
I'm using DEV C++ compiler on my PC and I have no problem with char, but strings give me fits.

That did the trick thanks.
The reason is the preceding cin >> ans;

After the user inputs the value of ans, they press enter. That leaves a newline character sitting waiting in the input buffer. The next getline reads up to the newline (which is then discarded) meaning an empty line is read.

The purpose of using cin.ignore() is to get rid of that unwanted newline character.
Last edited on
Topic archived. No new replies allowed.