从文件 c++ 中的下一行读取

Reading from the next line in a file c++

本文关键字:一行 读取 文件 c++      更新时间:2023-10-16

我正在尝试制作一个库存系统,该系统从列表中读取并将内容存储在并行向量中。我的向量在我包含在代码中的类中设置为公共成员。文本文件如下所示

1111
Dish Washer
20 250.50 550.50
2222
Micro Wave
75 150.00 400.00
3333
Cooking Range 
50 450.00 850.00
4444
Circular Saw
150 45.00 125.00
6236
Tacos
200 5.00 5.50

这是我的代码

 int main()
{
    char choice;
    Inventory Stocksheet(5); // the included list has 5 items if a text file has more then it should scale fine
    int id, ordered;
    string name;
    double manuprice, price;
    ifstream data;
    data.open("Inventory Data.txt");
    if (data.fail())
    {
        cout << "Data sheet failed to open n";
        exit(1);
    }
    while (data >> id )
    {
        Stocksheet.itemID.push_back(id);
        getline(data,name);
        Stocksheet.itemName.push_back(name); // this is where my code fails
        data >> ordered;
        Stocksheet.pOrdered.push_back(ordered);
        Stocksheet.pInstore.push_back(ordered);
        data >> manuprice;
        Stocksheet.manuPrice.push_back(manuprice);
        data >> price;
        Stocksheet.sellingPrice.push_back(price);
    }
    do
    {
        cout << "     Your friendly neighborhood tool shackn";
        cout << "Select from the following options to proceed n";
        cout << "1. Check for item n";
        cout << "2. Sell an iem n";
        cout << "3. Print Report n";
        cout << "Input any number other than 1,2 or 3 to exit n";
        cout << "Selection : ";
        cin >> choice; // think about sstream here
        switch (choice)
        {
        case '1': checkforitem(Stocksheet);
            break;
        case '2': sellanitem(Stocksheet);
            break;
        case '3': printthereport(Stocksheet);
            break;
        default: cout << " ^-^ Exiting the shop. Have a fantastic day! ^-^ n";
            break;
        }
    }while ((choice == '1') || (choice == '2') || (choice == '3'));
    data.close();
    return 0;
}

我评论了我的代码中断的地方。在 while 循环中,数字 id 被推送到我的第一个向量,但名称为空,之后的每个值都留空。我的循环设置方式有问题吗?

当你使用>>运算符时,你会得到一个"word"类型的东西。它停止在空白处。因此,当您调用 getline 时,它会读取第一行末尾的换行符(上面有 id)并停止。所以你的name是空白的。

您可以在切换到getline之前调用data.ignore(),这将处理换行符。小心将>>运算符与getline混合。它没有达到您的期望。