Respuesta :
Answer:
//main.cpp
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
//function prototypes
int calcPastries(string filename);
int split(string s, char sep, string words[], int max_words);
//start of main function
int main()
{
//Set file name
string fname="inputfile.txt";
//call function, calcPastries
calcPastries(fname);
system("pause");
return 0;
}
/*The function, calcPastries thta takes a string file name and then read the file and split the line of text using
split function. The method prints the data of the file on console */
int calcPastries(string fname)
{
//Open file for reading
ifstream fin;
fin.open(fname);
//check if file not exists
if(!fin)
{
cout<<"File Not Found."<<endl;
return -1;
}
double total=0;
int lineCount=0;
string words[3];
int max_words=3;
string linetext;
/*read file ,find to end of file */
while(!fin.eof())
{
getline(fin,linetext,'\n');
//call the split function
split(linetext, ',',words,max_words );
//print the data to console
cout<< words[0]<<":"<<stof(words[1])*stof(words[2])<<endl;
/*Convert string to float and then multiply then add to total*/
total+=stof(words[1])*stof(words[2]);
//increment the linecount by 1
lineCount++;
}
//print total value on console
cout<<"Total :"<<total<<endl;
return lineCount;
}
/*The split function takes a string ,delimiter , arrary of string type and maxwords to split and then split the string and store the tokens into the string,word array and then print the data to console.*/
int split(string s, char sep, string words[], int max_words)
{
char delimiter=sep;
std::string token;
std::istringstream tokenStream(s);
int counter=0;
while(getline(tokenStream, token, ','))
{
words[counter]=token;
counter++;
}
return counter;
}
Explanation: