我很難看出爲什麼我的代碼不起作用。出現問題的部分是當我將文本文件中的值傳遞給我的等級變量時。我不明白爲什麼這是錯的。無論如何,我的代碼的其他一切都很好,但我還是把它包括在內了。從文本文件讀入矢量
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