Home > Enterprise >  how to working with files in c in this sample code?
how to working with files in c in this sample code?

Time:03-30

in this project, we can add product information and save them into a file <product.txt>.notice that the file name can include space and it can be muluti_piece -->Ex)Samsung air conditioner. but for reading the name from file in the 'edit' Function I have to use getline function. but when I use getline in edit function for reading data, File entries are corrupted. how can I fix it ?

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

}

CodePudding user response:

the way to solve this problem is put a Product_For_read.ignore(); on top the problem line .

  • Related