我想计算总的和平均数据从文本文件使用c++

I want to calculate total and average of data from text file using C++

本文关键字:文本 文件 c++ 数据 计算      更新时间:2023-10-16

我想用c++计算文本文件中数据的总数和平均值。
这是我的代码和文本文件。这段代码在运行

时没有显示任何内容。
#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;
}

将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; 
}

这是我的文本文件data.txt

  234
  456
  789

需要使用while循环。您只读取一行,所以您需要确保您一直读取到文件的末尾。

另外,您可能希望使用标准库函数:std::stoi是适用于std::string的c++ 11及其后续版本,但<cstdlib>std::atoistd::string.c_str()一样适用。

#include <iostream>
#include <fstream>
#include <string>
//Compile with C++11; -std=c++11
int main(int argc, char** argv) {
    std::fstream file;
    //Open the file
    file.open(argv[1]);
    std::string buffer = "";
    int sum = 0;
    int n = 0;
    //Check for file validity, and keep reading in line by 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;
}