2012-12-03 112 views
0

可能重复:
Use getline and >> when read file C++函数getline之后第一次被跳过的for循环

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); 

} 

这是我尝试运行的功能。它在第一次运行良好,但第二次围绕getline不读取书的标题并跳过它。然后它会在第二个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(); 
} 
}    
+0

该cout不会在那里。我只是把它放入来检查数据是否正确地放入结构数组中。 – TripleKyu

+5

你正在阅读的文件是什么样的? – shf301

+1

不要结合使用'getline'和'>>'。许多类似的问题,但简短的版本是'getline'删除''\ n'','>>'不。 – BoBTFish

回答

0

首先,做一个快速检查,如果失败或坏位上,因为当失败位上,它可能会从能够做读取操作阻止文件流。您可能会错误地尝试将字符串读入一个整数,例如会引发失败位。