我认为简化您发布的代码比试图找到所有可能出错的地方更容易。
如果您希望在文件中只看到double 值,您可以将用于从文件中读取数据的代码简化为:
while ( data_file >> new_data_pt )
{
// Use new_data_pt
}
如果您预计可能存在doubles 以外的值,那么您可以使用:
while ( getline(data_file, line) )
{
std::istringstream str(line);
while ( str >> new_data_pt )
{
// Use new_data_pt
}
}
但是您必须了解代码在遇到错误后不会再从一行中读取任何值。如果您的行包含
10.2 K 25.4
代码将读取10.2,在K遇到错误,并且不会处理25.4。
处理new_data_pt的代码是需要存储在一个动态分配的数组中。我建议把它放在一个函数中。
double* add_point(double* data_ptr, int data_len, double new_data_pt)
将该函数调用为:
data_ptr = add_point(data_ptr, data_len, new_data_pt);
假设第一个while循环,main的内容变成:
int main()
{
std::fstream data_file{ "millikan2.dat" };
// It is possible that the file has nothing in it.
// In that case, data_len needs to be zero.
int data_len{ 0 };
// There is no need to allocate memory when there is nothing in the file.
// Allocate memory only when data_len is greater than zero.
double* data_ptr = nullptr;
double new_data_pt;
if (!data_file.good()) {
std::cerr << "Cannot open file";
return 1;
}
while ( data_file >> new_data_pt )
{
++data_len;
data_ptr = add_point(data_ptr, data_len, new_data_pt);
}
// No need of this.
// The file will be closed when the function returns.
// data_file.close();
}
add_point 可以实现为:
double* add_point(double* data_ptr, int data_len, double new_data_pt)
{
double* new_data_ptr = new double[data_len];
// This works even when data_ptr is nullptr.
// When data_ptr is null_ptr, (data_len - 1) is zero. Hence,
// the call to std::copy becomes a noop.
std::copy(data_ptr, data_ptr + (data_len - 1); new_data_ptr);
// Deallocate old memory.
if ( data_ptr != nullptr )
{
delete [] data_ptr;
}
new_data_ptr[data_len-1] = new_data_pt;
return new_data_ptr;
}
跟踪坏点数量的代码要复杂得多。除非您必须这样做,否则我建议您忽略它。