0

Im trying to do a very simple thing, read numbers from a file using ifstream in C++. My input file called 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

My code to read these lines goes as follows:

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];

I get this error when I output what it has read:

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

I dont understand what I am doing wrong. I thought the >> takes care of the tab spaces.

user1705329
  • 45
  • 1
  • 6

2 Answers2

2

factor is declared as an int; it should be a float or double. And similarly for unit_cell, which isn't declared in your sample code.

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
1

I agree with @JosephQuinsey. Here's the code I wrote as a test:

#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;
}
Joe Bane
  • 1,556
  • 1
  • 15
  • 30