hey guys ! i have been given an assignment . the question is stated below :
1. Create a struct Product with fields id (int), name (char*), price (double), and isAvailable (bool).
2. Write a function which returns a pointer to a dynamically allocated Product filled with the provided data.
Product * getNewProduct(int id, char * name, int nameLength, double price, bool isAvailable);
3. Write a function to read data of products from a file and fill it in a dynamically allocated array of Products and return it. Here is the format of the file.
3
1234 Phone 4400.22 0
1111 Laptop 34999.99 1
9087 Burger 45.00 0
|
The first line contains an integer the number of products, on each of the following lines there is data for each product in following format
<id><name><price><isAvailable>
The name will not contain any spaces.
4. Write a function that takes a Product * (which points to the array of products) and an integer id. The function searches the product with that id in the array and returns a pointer to that Product if found. The function returns NULL otherwise.
5. Write a function that takes a Product * and a char * name. The function searches the product with that name in the array and returns a pointer to that Product if found. The function returns NULL otherwise.
so far i have done the first three parts of this question but i have some problem . my code is pasted below :
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std ;
struct Product
{
int id ;
char *name ;
double price ;
bool isAvailable ;
};
Product* getNewProduct(int id, char* name , double price , bool isAvailable );
bool* ReadData (ifstream &inFile, Product P[] );
int main ()
{
system("pause");
return 0 ;
}
Product* getNewProduct(int id, char* name , double price , bool isAvailable )
{
Product *P = new Product ;
(*P).id = id ;
(*P).isAvailable = isAvailable ;
(*P).name = name ;
(*P).price = price ;
return P ;
}
bool* ReadData (ifstream &inFile , Product P[] )
{
ifstream inFile ;
int size ;
string line ;
bool isAvailable ;
inFile.open("file.txt");
if (!inFile.is_open())
{
cout << " opening of file failed " << endl;
exit(1);
}
while (!inFile.eof())
{
inFile >> size ;
Product *arr = new Product [size];
for (int i = 0 ; i<size ; i++ )
{
getline (inFile,line,' ' );
P[i].id = atoi(line); // gives error (underlines line stating that no suitable conversion from std::string to const char* exists )
P[i].name = getline(inFile,line,' ' ); // gives error underlining "getline"
getline (inFile,line,' ' );
P[i].price = atof(line); // gives error (underlines line stating that no suitable conversion from std::string to const char* exists )
P[i].isAvailable = inFile >> isAvailable ;
}
}
}