2012-07-22 23 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