【问题标题】:getline being skipped after first time in for loop [duplicate]第一次在for循环中跳过getline [重复]
【发布时间】:2012-12-03 16:18:48
【问题描述】:

可能重复:
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);

}

这是我正在尝试运行的功能。它第一次运行良好,但第二次围绕 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();
}   
}            

【问题讨论】:

标签: c++ for-loop getline


【解决方案1】:

首先,快速检查失败或坏位是否打开,因为当失败位打开时,它可能会阻止文件流进行读取操作。您可能会错误地将字符串读入整数,例如引发失败位。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多