我很难看出为什么我的代码不起作用。出现问题的部分是当我将文本文件中的值传递给我的等级变量时。我不明白为什么这是错的。无论如何,我的代码的其他一切都很好,但我还是把它包括在内了。从文本文件读入矢量
string fileName;
cout << "Program that takes data from file and calculate\nmean and standard deviation and put it in file out.txt\n";
cout << "Enter the input file name ";
cin >> fileName;
double grade;
ifstream inData;
inData.open(fileName.c_str());
// Declare vector<double> vecx
vector<double> vecx;
// read data from input file to vector vecx,
while(inData >> grade)
{
vecx.push_back(grade);
}
inData.close();
// keep track how many elements you read from file
// When you done with reading from file, close stream inData
这里是完整的代码,如果你有兴趣。
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
string fileName;
cout << "Program that takes data from file and calculate\nmean and standard deviation and put it in file out.txt\n";
cout << "Enter the input file name ";
cin >> fileName;
double grade;
ifstream inData;
inData.open(fileName.c_str());
// Declare vector<double> vecx
vector<double> vecx;
// read data from input file to vector vecx,
while(inData >> grade)
{
vecx.push_back(grade);
}
inData.close();
// keep track how many elements you read from file
// When you done with reading from file, close stream inData
// read element by element in vector vecx and calculate sum;
double sum=0;
double average;
for (int i=0; i < vecx.size(); i++)
sum=sum+vecx[i];
average=sum/(vecx.size());
// sum divide by number of elements to find mean(average)
//again read element by element and calculate
//square of difference between element and mean
//calculate sum of squares of differences
//divide by number of elements and
//take square root - you got the standard deviation
sum=0;
double variance, stdev;
for (int i=0; i < vecx.size(); i++)
sum=sum+(vecx[i]-average*vecx[i]-average);
variance=sum/(vecx.size());
stdev=sqrt(variance);
//open output stream
ofstream outData;
outData.open("out.txt");
//output mean and standard deviation
cout << "Average is " << average << endl;
cout << "Standard deviation is " << stdev << endl;
//close stream
outData.close();
}
我感觉自己就像没有看到为什么这是不工作...我应该能想出解决办法,但我不是白痴。
如果您发布了您正在获取的错误,而不是简单地“它不起作用”,这将会很有帮助。 – SShaheen 2013-02-12 16:48:54
究竟是什么问题?读完之后'vecx'是空的吗? – David 2013-02-12 16:48:58
没有看到数据文件(它必须是以空格分隔的**文本**表示双值),*和*知道文件已成功打开(在当前源中永远不会验证),因此无法回答这准确。你能详细说明“它不工作”的*确切的意思吗? – WhozCraig 2013-02-12 16:50:35