I want to calculate total and average of data from text file using C++ -
i want calculate total , average of data text file using c++.
here code , text file. code not showing on run
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; string double2string(double); double string2double(string); int main(int argc, char* argv[]){ fstream dfile; string s1; string amount; double damount; double sum = 0; dfile.open(argv[1]); dfile >> amount; damount = string2double(amount); while(damount){ sum = sum + damount; } string total = double2string(sum); dfile.clear(); dfile.close(); cout << total; return 0; }
functions convert string double , double string
string double2string(double d){ ostringstream outstr; outstr << setprecision(2) << fixed << setw(10) << d; return outstr.str(); }; double string2double(string s1){ istringstream instr(s1); double n; instr >> n; return n; }
here text file "data.txt"
234 456 789
you need use while loop. you're reading in 1 line, need make sure keep reading in lines until end of file.
also, might want use standard library function: std::stoi
c++11 , onward version works std::string
, std::atoi
<cstdlib>
works std::string.c_str()
.
#include <iostream> #include <fstream> #include <string> //compile c++11; -std=c++11 int main(int argc, char** argv) { std::fstream file; //open file file.open(argv[1]); std::string buffer = ""; int sum = 0; int n = 0; //check file validity, , keep reading in line line. if (file.good()) { while (file >> buffer) { n = std::stoi(buffer); sum += n; } std::cout << "sum: " << sum << std::endl; } else { std::cout << "file: " << argv[1] << "is not valid." << std::endl; } return 0; }
Comments
Post a Comment