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

AK0*_*K02 2 c++ ifstream ofstream

我有一个数据文件(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
Run Code Online (Sandbox Code Playgroud)

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

0.0000        0.00000
1.0000        90.0000
2.0000        180.0000
3.0000        360.0000
Run Code Online (Sandbox Code Playgroud)

我试过这个:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

我在B.dat中得到这个:

0       6.95272e-310
6.95272e-310    6.93208e-310
1.52888e-314    2.07341e-317
2.07271e-317    6.95272e-310
Run Code Online (Sandbox Code Playgroud)

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

Gal*_*lik 5

我经常使用std :: 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';
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

{0.0000, 0.0000}
{1.0000, 90.0000}
{2.0000, 180.0000}
{3.0000, 360.0000}
Run Code Online (Sandbox Code Playgroud)

注意:

我将阅读陈述置于while()条件之内.这是有效的,因为从流中读取会返回对象,当放入if()或处于while()条件状态时,true如果读取成功或false读取失败则返回.

因此,当您用完数据时,循环终止.