跳过从数据文件C ++读取字符 [英] Skip reading characters from a data file C++
问题描述
我有一个具有以下格式的数据文件(A.dat):
I have a data file (A.dat) with following format:
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)中,如下所示:
I want to read the values (only) of theta and phi and store them in a data file (B.dat) like this:
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中得到了这个
I get this in B.dat:
0 6.95272e-310
6.95272e-310 6.93208e-310
1.52888e-314 2.07341e-317
2.07271e-317 6.95272e-310
如何跳过阅读字符和其他内容,只保存数字?
How do I skip reading characters and other things and save only the digits?
推荐答案
我经常使用 std :: getline 跳过过去不需要的数据,因为它允许您读取(并过去)特定字符(在本例中为'='):
I often use std::getline to skip past unwanted data because it allows you to read up to (and past) a specific character (in this case the '='):
#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
.
I put the reading statements inside the while()
condition. This works because reading from a stream returns the stream object and when put into an if()
or a while()
condition it returns true
if the read was successful or false
if the read failed.
因此,当数据用完时,循环终止.
So the loop terminates when you run out of data.
这篇关于跳过从数据文件C ++读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!