如何在此示例代码中使用 C++ 中的文件?

how to working with files in c++ in this sample code?

在这个项目中,我们可以添加产品信息并保存到文件中。注意文件名可以包含space,也可以是muluti_piece - ->Ex)三星空调。 但是要从 'edit' 函数中的文件中读取名称,我必须使用 getline 函数。但是当我在编辑功能中使用 getline 读取数据时,文件条目已损坏。我该如何解决?

#include <iostream>
#include<string.h>
#include<string>
#include <stream>
#include <windows.h>

using namespace std;

void edit(int& j)
{
int step = 0;
int price[100], number[100], code[100];

string name[100];
ifstream Product_For_read;

Product_For_read.open("C:\PROJECTS\PROJECT2\ConsoleApplication1\products.txt");
while (Product_For_read >> code[step])
{
    getline(Product_For_read,name[step],'\n'); // this Is the problem !!!!!!
    Product_For_read >> number[step];
    Product_For_read >> price[step];
    step++;
}
Product_For_read.close();
int counter = step;
bool flag = false;
for (int step1 = 0; step1 <= counter; step1++)  // editing data from file
{
    if (step1 == j)
    {
        flag = true;
        cout << "\n edite the product name : \n";
        cin.ignore();
        getline(cin, name[step1], '\n');

        cout << "\nedite the product numebr  of count : ";
        cin >> number[step1];
        cout << "\nedite the product price : ";
        cin >> price[step1];
    }
}
if (flag == true)
{
    ofstream product_for_write; //write data to file
    product_for_write.open(("C:\PROJECTS\PROJECT2\ConsoleApplication1\products.txt"));
    for (int step2 = 0; step2 < counter; step2 ++)
    {
        product_for_write << code[step2] << endl << name[step2] << endl << number[step2] << endl << price[step2] << endl;
    }
    product_for_write.close();
}

}

void apply_product()
{
string title;
int code, number, price;

cout << " product code : ";
cin >> code;
cin.ignore();
cout << " product name : ";
getline(cin, title, '\n');
cout << " product number : ";
cin >> number;
cout << " product price : ";
cin >> price;

ofstream Product_For_write;
Product_For_write.open("C:\PROJECTS\PROJECT2\ConsoleApplication1\products.txt", ios::app);
Product_For_write << code << endl << title << endl << number << endl << price << endl;
Product_For_write.close();

cout << "\n\n product added successfully ....\n";
}

int main()
{
int i;

    cout << "1-add a product\n2-edit product\n";
    cin >> i;
    if (i == 1)
        apply_product();
    else if (i == 2)
    {
        int j;
        cout << "which one of items do you want to edit?-->";
        cin >> j; //user will enter the code of item which is the product code [0,1,2,...]
        edit(j);
    }

}

解决这个问题的方法是 Product_For_read.ignore();在问题行之上。