[英]C++ Data file with an unwanted character: How to remove rogue character and calculate mean, standard deviation and standard error
我有一個包含49個數字+ 1個單詞的數據文件,另一個包含50個數字的文件。 我的任務是計算兩者的均值,標准差和標准誤差。 目前,我有一個代碼,可以很高興地為僅包含數字的文件計算正確的值。 如何刪除角色?
我是一個初學者,不確定如何正確使用getline()函數將文件中的數據放入字符串中,然后以某種方式使用cin.ignore()和cin.clear()刪除字符? 幫助將不勝感激!
程序:
// Assignment 2: Milikan data programme
#include "stdafx.h"
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cmath>
#include<string>
using namespace std;
//Mean function
double mean(double *mydata, double N)
{
double sum(0), m;
for (int i=0; i<N; i++)
{
sum += mydata[i];
}
m = (sum/(double)N);
return(m);
}
//Standard deviation function
double standard_dev(double *mydata, double m, int N)
{
double *mydata2 = new double[N];
for (int i=0; i<N; i++)
{
mydata2[i] = pow((mydata[i]-m), 2);
}
double sum(0), S, X;
for (int i=0; i<N; i++)
{
sum += mydata2[i];
}
X = sum/(N-1);
S = sqrt(X);
return (S);
}
int main ()
{
int N(0);
char filename[100];
double m, sterr, stdev;
string temp;
cout<<"Please enter the number of data points: ";
cin>> N;
cout<<"Please enter the name of the file: ";
cin>>filename;
//Dynamic memory allocation for N data points in array mydata
double *mydata;
mydata = new double[N];
//Open file and attach chosen file to myfile
ifstream myfile;
myfile.open(filename);
//Check it opened sucessfully
if(!myfile.is_open())
{
cerr<<"\nError: file could not be opened!"<<endl;
system("PAUSE");
return(1);
}
//Detect and ignore rogue character???
//Read data from the file into an array
for (int i=0; i<N; i++)
{
myfile>>mydata[i];
}
m = mean(mydata, N);
stdev = standard_dev(mydata, m, N);
sterr = 1/stdev;
cout<<"\nThe mean charge of an electron is : "<<m<<" eV"<<endl; /
cout<<"The standard deviation of results is : "<<stdev<<endl;
cout<<"The standard error of results is : "<<sterr<<endl;
myfile.close(); //Close file
delete[] mydata; // Free memory
system("PAUSE");
return 0;
}
還要記住,如果數字提取失敗,流對象的故障failbit
將被置failbit
。 您可以進行檢查,如果已設置,則跳過流中的所有非數字字符,直到再次看到數字。
像這樣的偽代碼:
while (myfile)
{
myfile >> value;
if (myfile.fail())
{
clear_failbit();
while (next_character_is_not_digit())
get_and_discard_next_character();
}
}
當然,更好的解決方案可能是不生成包含錯誤的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.