我试图做一个非常简单的事情,在C ++中使用ifstream从文件中读取数字。 我的输入文件名为POSCAR
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
我不明白我做错了什么。我以为&gt;&gt;照顾标签空间。
答案 0 :(得分:2)
factor
被声明为int
;它应该是float
或double
。类似于unit_cell
,未在示例代码中声明。
答案 1 :(得分: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;
}