0

我有一个包含 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;
}
4

1 回答 1

0

还要记住,failbit如果数字提取失败,则流对象将被设置。你可以检查一下,如果设置了,你会跳过流中的所有非数字字符,直到你再次看到一个数字。

像这样的伪代码:

while (myfile)
{
    myfile >> value;

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

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

当然,更好的解决方案可能是生成包含错误的文件。

于 2013-02-13T13:54:42.743 回答