2013-02-13 11 views
0

我有一個數據文件,其中包含49個數字+ 1個字和另一個包含50個數字的文件。我的任務是計算兩者的均值,標準差和標準誤。目前,我有一個代碼,它將愉快地計算包含數字的文件的正確值。我如何刪除角色?我不知道如何正確使用getline()函數將文件中的數據放入字符串中,然後以某種方式使用cin.ignore()和cin.clear()來移除字符?幫助將不勝感激!帶有不需要字符的C++數據文件:如何刪除流氓字符並計算平均值,標準差和標準差

計劃:

// 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; 
} 
+0

每個數字都在一個單獨的行上?不需要的字符或字符串是否在單獨的行上? – 2013-02-13 13:52:08

+0

請不要將該文件置於評論中,而應將其摘錄在問題中。 – 2013-02-13 13:56:03

+0

1.64638錯誤1.55023 1.54612 1.54004等.... – user2068527 2013-02-13 13:56:06

回答

0

還記得那failbit變成一個數的提取失敗設置的流對象。你可以檢查,如果設置你跳過流中的所有非數字字符,直到你再次看到一個數字。

事情是這樣的僞代碼:

while (myfile) 
{ 
    myfile >> value; 

    if (myfile.fail()) 
    { 
     clear_failbit(); 

     while (next_character_is_not_digit()) 
      get_and_discard_next_character(); 
    } 
} 

當然,一個更好的解決辦法可能是生成包含錯誤的文件。