[英]Reading floats from a .txt file in C++
您好,我在读取.txt文件中用空格分隔的浮点列表时遇到麻烦。 我想将从文件中读取的数字存储在向量中,然后从它们中获取一些信息(总和,中位数,众数等),但我什至无法获取存储在向量中的值。 代码段如下:
#include <vector>
#include <fstream>
#include <iostream>
int main(){
std::ifstream myFile; //creates stream myFile
myFile.open("simpledata.txt"); //opens .txt file
std::vector<double>numberlist; //vector to store the numerical values in
double number = 0 ;
while(myFile >> number){ //
numberlist.push_back(number);
for (int i = 0; i < numberlist.size(); i++){
std::cout << numberlist[i] << std::endl ;
}
double sum = 0;
for (int i = 0; i< numberlist.size(); i++){ //calculates sum
sum += numberlist[i];}
std::cout << "Average number: " << sum/numberlist.size() << std::endl; //prints average
}
当我运行该程序时,平均值输出为“ -1。#IND”,这显然不是我想要的。 我真的很感谢您的帮助。 我对编程非常陌生,因此如果此代码特别糟糕,我深表歉意。
添加此代码
std::ifstream myFile; //creates stream myFile
myFile.open("simpledata.txt"); //opens .txt file
if (!myFile.is_open()) // check file is open, quit if not
{
std::cerr << "failed to open file\n";
return 1;
}
看来您打开文件确实失败了,这就是为什么您无法读取任何浮点数的原因。
该代码将验证该理论。 打开文件时,请始终检查打开是否成功。
关于从文本文件读取和写入浮点数的一个棘手问题是标准库考虑了语言环境。 这意味着如果语言环境将小数点定义为逗号,则它将无法解析带有句点小数点的数字。 您应检查操作系统的语言环境设置和文本文件中的数字,小数点应相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.