2012-11-03 68 views
0

我試圖做一個非常簡單的事情,從文件中使用ifstream在C++中讀取數字。 我輸入文件名爲POSCAR總線錯誤C++讀取文件

supercell        
    1.00000000000000 
    7.3287291297858630 0.0000000000000000 0.0000000000000000 
    0.0000000000000000 7.3287291297858630 0.0000000000000000 
    0.0000000000000000 0.0000000000000000 7.3287291297858630 
    Au Cu 
    1 31 

我的代碼來讀取這些行去如下:

ifstream poscar("POSCAR"); 
    getline(poscar,skip); //Skipping comment first line 
    cout<<skip<<endl; 
    // Reading in the cubic cell coordinates 
    int factor; 
    poscar>>factor; 
    cout<<factor<<endl;  
int nelm[10]; // number of elements in the alloy 
    float ax,ay,az,bx,by,bz,cx,cy,cz; 
    poscar>>unit_cell[0][0]>>unit_cell[0][1]>>unit_cell[0][2]; 
    poscar>>unit_cell[1][0]>>unit_cell[1][1]>>unit_cell[1][2]; 
    poscar>>unit_cell[2][0]>>unit_cell[2][1]>>unit_cell[2][2]; 

我得到這個錯誤,當我輸出的是什麼已經閱讀:

supercell        
1inf7.328730 
0inf7.32873 
7.3287291297858630 
-142571760010922 
Bus error 

我不明白我做錯了什麼。我認爲「>>」會照顧標籤空間。

+2

'1.00000000000000'。文本形式的整數在它們中不能有小數點。 –

回答

2

factor被聲明爲int;它應該是floatdouble。同樣的unit_cell,這是沒有在您的示例代碼中聲明。

+1

謝謝!這修正了錯誤! – user1705329

1

我同意@JosephQuinsey。這裏是我寫作測試的代碼:

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

int main() 
{ 
    string skip; 
    ifstream poscar("/tmp/POSCAR.txt"); 
    getline(poscar, skip); 
    cout << skip << endl; 

    while (poscar.good()) 
    { 
     double factor; 
     poscar >> factor; 
     cout << factor << endl; 
    } 

    poscar.close(); 
    return 0; 
}