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

标签 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

我想(仅)读取 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跳过不需要的数据,因为它允许您读取(和过去)特定字符(在本例中为“=”):

#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';
    }
}

输出:

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

注意:

我把阅读语句放在while()里面健康)状况。这是有效的,因为从 stream 读取返回 stream 对象,当放入 if() 时或 while()它返回的条件 true如果读取成功或 false如果读取失败。

所以当你用完数据时循环终止。

关于c++ - 跳过从数据文件 C++ 中读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39345902/

相关文章:

c++ - MFC/C++ : Need distant "wall clock" time without resetting my system's time

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - 这种方法会涉及内存重新分配从而影响其效率吗?

c++ - istream 在 DEV C++ 中不工作

C++ 打开文件并向类对象输入数据

c++ - 如何保存文件中的所有数据? C++

c++ - 打开路径名中带有波浪号 (~) 的 ofstream

c++ - cmake选项默认值

c++ - ROS:我们能得到一个由launchfile启动的节点列表吗

C++ ofstream 与 C++ cout 管道传输到文件