I have encountered some problem when i tried to read the data using binary mode, which I cant read the data that I wanted.
//this is my code
#include <iostream>
#include <fstream>
using namespace std;
struct ChemicalElement
{
int atomicNumber;
char name[100];
char symbol[3];
float mass;
};
void readrecord(ChemicalElement element);
int main()
{
ChemicalElement element;
return 0;
}
void readrecord(ChemicalElement element)
{
ifstream in;
in.open("chemicalElements.txt",ios::in | ios::binary);
if(!in)
{
cout<<"File not found"<<endl;
}
else
{
in.read((char*)(&element),sizeof(element.mass));
cout<<"Element mass: "<<element.mass<<endl;
}
}
I tried to read the file which is formatted as below:
9.0122 Beryllium Be 4
10.811 Boron B 5
247 Curium Cm 96
247 Berkelium Bk 97
12.0107 Carbon C 6
but what I get after I compiled is totally different. Can someone help me and explain whats wrong with my code. Thanks ^^
Last edited on
Your main function doesn't do anything. Well it declares a variable, then exits
1 2 3 4 5
|
int main()
{
ChemicalElement element;
return 0;
}
|
You should call the function
readrecord()
if you want that code to be executed.
Your file consists of text, hence you should not be trying to read it like this,
|
in.read((char*)(&element),sizeof(element.mass));
|
(Also no need to open it in binary mode).
Your code needs to read each of the four data members individually. Possibly something like this:
|
in >> element.mass >> element.name >> element.symbol >> element.atomicNumber;
|
Last edited on
I know where's the problem, its my txt file. Thanks Chervil ^^