如何在不使用提取运算符的情况下计算文本文件中的数字?

问题描述 投票:-1回答:1

我有一个名为'sample.txt'的txt文件,其中包含表单的数据

1.0

2.1

ABC

4.2

我想从txt文件中提取数字1.0,2.1,4.2并忽略字符串'abc'。

在我提取数据之前,我想首先确定txt文件中有多少个数字。

因为我想将数字提取到动态数组中,我需要知道要先创建的数组大小。

我的用于计算txt文件中的数字的代码是

ifstream myfile; 
myfile.open ("sample.txt"); 

int dataCount = 0;  // to count number of numbers

while (!myfile.eof())
{
    double x;         
    myfile >> x;    

    if (myfile.fail()) // no extraction took place
    {
        myfile.clear(); 
        myfile.ignore(numeric_limits<streamsize>::max(), '\n'); 
        continue;  // do nothing and start reading next data
    }

    // Count up if x successfully extracted
    dataCount++;
}

所以现在我已经完成了数字的数量,但ifstream myfile中也没有任何内容可供我提取。无论如何计算数字而不从ifstream myfile中提取任何东西?

这是为了我不允许使用矢量的学校作业。

c++ c++11 fstream ifstream
1个回答
3
投票

您可以关闭该文件并再次打开它。或者你可以清除文件结束标志并回到开头。

myfile.clear();
myfile.seekg(0); // rewind the file to the beginning
© www.soinside.com 2019 - 2024. All rights reserved.