我想计算总的和平均数据从文本文件使用c++
I want to calculate total and average of data from text file using C++
我想用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::atoi
与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++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入