Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a function named CalcCost , which takes a string input filename and strin

ID: 3595873 • Letter: C

Question

Create a function named CalcCost, which takes a string input filename and string output filename as a parameter. This function returns the number of entries read from the file. If the input file cannot be opened, return -1 and do not print anything to the output file.

Read each line from the given filename, parse the data, process the data, and print the required information to the output file.

Each line of the file contains PRODUCT NAME, COST PER ITEM, QUANTITY. Read and parse the data, then output the total cost for each entry.

If given the data below:

Your output file should contain:

You only need to write the function code. Our code will create and test your function.

Explanation / Answer

int CalcCost(string inputfilename, string outputfilename){
// PRODUCT NAME, COST PER ITEM, QUANTITY
// Looking for name and multiplied values

int entries_read = 0;
string output_string = "";

ifstream input;
input.open(inputfilename);

if (input.fail()){
    // File opening failed
    //cout << "Input file opening failed." << endl;
    return -1;
} else {
    // File opening suceeded
    string line;
    while(getline(input,line)){
        string name = "";
        double cost = 0;
        int quantity = 0;
      
        istringstream ss(line);
        int index = 0;
        string result;
       while(getline(ss, result, ',')) {
            if(index==0){
                name = result;
            } else if(index==1){
                result = result.substr(1, result.length()-1);
                cost = stod(result);
            } else if(index==2){
                result = result.substr(1, result.length()-1);
                quantity = stoi(result);
            }
            index++;
       }
       double tot = (cost*quantity);
       string num_str = to_string(tot);
       while(num_str[num_str.length()-1]=='0'){
            if(num_str[num_str.length()-2]=='.'){
                num_str = num_str.substr(0, num_str.length()-2);
                break;
            }else{
                num_str = num_str.substr(0, num_str.length()-1);
            }
       }
      
       output_string = output_string + name + ": " + num_str + " ";
      
       entries_read++;
    }
    input.close();
  
    ofstream output;
    output.open(outputfilename);
    if (output.fail()){
        cout << "Error writing file" << endl;
    } else {
        output << output_string;
        output.close();
    }
}

return entries_read;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote