gpt4 book ai didi

c++ - 我想使用 C++ 计算文本文件中数据的总数和平均值

转载 作者:太空宇宙 更新时间:2023-11-04 13:33:35 25 4
gpt4 key购买 nike

我想使用 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;
}

将字符串转换为 double 和将 double 转换为字符串的函数

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 及更高版本,但是 std::atoi来自 <cstdlib>std::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;
}

关于c++ - 我想使用 C++ 计算文本文件中数据的总数和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com