跳过从数据文件中读取字符 C++

2024-03-19

我有一个具有以下格式的数据文件(A.dat):

Theta = 0.0000        Phi = 0.00000
Theta = 1.0000        Phi = 90.0000
Theta = 2.0000        Phi = 180.0000
Theta = 3.0000        Phi = 360.0000

我想(仅)读取 theta 和 phi 的值并将它们存储在数据文件(B.dat)中,如下所示:

0.0000        0.00000
1.0000        90.0000
2.0000        180.0000
3.0000        360.0000

我试过这个:

    int main()
    {

      double C[4][2];

      ifstream fR;
      fR.open("A.dat");
      if (fR.is_open())
        {
          for(int i = 0; i<4; i++)
            fR >> C[i][0] >> C[i][1];  
        }
      else cout << "Unable to open file to read" << endl;
      fR.close();

      ofstream fW;
      fW.open("B.dat");

      for(int i = 0; i<4; i++)
        fW << C[i][0] << '\t' << C[i][1] << endl;

      fW.close();
    }

我在 B.dat 中得到了这个:

0       6.95272e-310
6.95272e-310    6.93208e-310
1.52888e-314    2.07341e-317
2.07271e-317    6.95272e-310

如何跳过读取字符和其他内容并仅保存数字?


我经常使用std::getline http://en.cppreference.com/w/cpp/string/basic_string/getline跳过不需要的数据,因为它允许您读取(并过去)特定字符(在本例中为“=”):

#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>

// pretend file stream
std::istringstream data(R"(
Theta = 0.0000        Phi = 0.00000
Theta = 1.0000        Phi = 90.0000
Theta = 2.0000        Phi = 180.0000
Theta = 3.0000        Phi = 360.0000
)");

int main()
{

    double theta;
    double phi;
    std::string skip; // used to read past unwanted text

    // set printing format to 4 decimal places
    std::cout << std::fixed << std::setprecision(4);

    while( std::getline(data, skip, '=')
        && data >> theta
        && std::getline(data, skip, '=')
        && data >> phi
    )
    {
        std::cout << '{' << theta << ", " << phi << '}' << '\n';
    }
}

Output:

{0.0000, 0.0000}
{1.0000, 90.0000}
{2.0000, 180.0000}
{3.0000, 360.0000}

NOTE:

我把阅读陈述放在while()健康)状况。这是有效的,因为从stream返回stream对象并当放入if() or a while()返回的条件true如果读取成功或者false如果读取失败。

因此,当数据用完时,循环就会终止。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

跳过从数据文件中读取字符 C++ 的相关文章

随机推荐