2012-07-22 25 views
1

这是我有一个文件的样本(这是一条线):阅读只能从字符串,字符的文件双打,双打

B12       MN =        1.2       G_{I}=       3.4        G_{B} =       9.4      J_k =        4.4     1.4      0.4     -0.1      -0.1    3.3     9.3      -5.7     2 

现在,我的问题是,我需要一个能够读取这个文件,并将我感兴趣的数字读入另一个文件。

所以,我尝试这样做:

ifstream in("Data.dat") 
ofstream out 
output.open("Output.dat") 

double a1, ..., a12; 

while(1) { 
      if(!(in >> a1 >> ... >> a12)) 
      break; 

      output << a1 << a2 << a12; //say these are the three doubles I'm interested in. 


} 

但是这并没有。我在输出文件中没有任何东西。我真的不知道如何解决这个问题。

有什么建议吗?

+1

'如果(!(在A1 >> >> ... >> A12)); “什么都不做。你确定最后应该有一个';'吗? – Aesthete 2012-07-22 03:46:05

+0

你可以把它们全部读成字符串,并用['stod'](http://en.cppreference.com/w/cpp/string/basic_string/stof)或['strtod']转换/跟踪有效的字符串(http://en.cppreference.com/w/cpp/string/byte/strtof)。 – chris 2012-07-22 03:47:22

+0

@Aesthete我纠正了这个问题,我试了一下。我猜这也是错误的。 – stupidity 2012-07-22 03:53:58

回答

2

您应该使用的,而不是 '双',测试代码 '字符串' 如下:

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main(int argc, char* argv[]) 
{ 
    ifstream in("t1.txt"); 
    string a1,a2,a3,a4,a5,a6,a7,a8,a9; 
    ofstream out("t2.txt"); 

    while(1) 
    { 
     if((in>>a1>>a2>>a3>>a4>>a5>>a6>>a7>>a8>>a9)) 
     { 
      out<<a1<<a3<<a5<<endl; 
     } 
     else 
      break; 
    } 

    return 0; 
} 
+0

非常感谢。这工作:D – stupidity 2012-07-22 04:20:13