0

Possible Duplicate:
Use getline and >> when read file C++

struct collection
{
    string title, author, isbn;
    float price;
    bool availability;
    int borrow;
};
void read1(member a[]);
void read2(collection b[]);
int main()
{
    member a[20];
    collection b[100];
    read1(a);
    read2(b);

}

This is the function that I'm trying to run. It runs fine the first time but the second time around the getline doesn't read the title of the book and skips it. It then ends up reading it later on in the second getline.

void read2(collection b[])
{
ifstream database;
string n1;
cout << "Enter second input file name: ";
getline(cin, n1);
database.open(n1.c_str());
if(database.fail())
{
    "Bad file. \n" ;
}
else
{
    for(int j=0;!database.eof();j++)
    {
        getline(database, b[j].title);
        cout << b[j].title<<endl;
        getline(database,b[j].author);
        cout<<b[j].author<<endl;
        database>>b[j].isbn;
        cout<<b[j].isbn<<endl;
        database>>b[j].price;
        cout<<b[j].price<<endl;
        database>>b[j].availability;
        cout<<b[j].availability<<endl;
        database>>b[j].borrow;
        cout<<b[j].borrow;
    }
    database.close();
}   
}            
Community
  • 1
  • 1
TripleKyu
  • 45
  • 3
  • The cout isn't going to be there later. I just put it in to check that the data is being put into the array of structures properly. – TripleKyu Dec 03 '12 at 16:19
  • 5
    What does the file you are reading look like? – shf301 Dec 03 '12 at 16:20
  • 1
    Don't combine use of `getline` and `>>`. Many similar questions, but the short version is `getline` removes the `'\n'` and `>>` doesn't. – BoBTFish Dec 03 '12 at 16:24
  • http://stackoverflow.com/questions/12622547/getline-function-not-working-with-multiple-string-input/12622636#12622636 – BoBTFish Dec 03 '12 at 16:25
  • 1
    And an additional issue you have with your code: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – interjay Dec 03 '12 at 16:27

1 Answers1

0

First, make a quick check if fail or bad bits are on, because when fail bit is on, it might block the file stream from being able to do reading operations. You may mistakenly trying to read a string into an integer, this is for example raises the fail bit.

StackHeapCollision
  • 1,504
  • 1
  • 11
  • 19