#include "default.h"
#include <fstream>
using std::ofstream;
using std::ifstream;
class Element
{
private:
string Symbol;
string Name;
int AtomNo;
public:
string rName() {return Name;}
string rSymbol () {return Symbol;}
int rAtomNo () {return AtomNo;}
Element SetAtom (int);
Element SetSymbol(string);
Element SetName(string);
};
Element Element::SetAtom(int a)
{
AtomNo = a;
return *this;
}
Element Element::SetSymbol(string a)
{
Symbol = a;
return *this;
}
Element Element::SetName(string a)
{
Name = a;
return *this;
}
int main ()
{
string Eleme[110];
ifstream Elem ("F:\\C++\\C++ Programs\\Periodic Table\\Element.txt");
if (Elem.is_open())
{
for(int i = 0;Elem.good() && i <110;i++)
{
getline (Elem, Eleme[i], '\n');
}
}
else
cout << "Unable to open File.";
Elem.close();
std::stringstream Buffer;
string A,B,C;
Element element[109];
for (int i = 0; i < 109; i++)
{
Buffer << Eleme[i];
getline (Buffer, A, '\t');
element[i].SetAtom(atoi(A.c_str()));
Buffer.str("");
getline (Buffer, B, '\t');
element[i].SetSymbol(B);
Buffer.str("");
getline (Buffer, C, '\t');
element[i].SetName(B);
}
cout << element[9].rName();
cin.get();
return 0;
}
Well this is my code.
The File has the content is the following form:
1 H Hydrogen
2 He Helium
3 Li Lithium
4 Be Berryllium
5 B Boron
6 C Carbon
7 N Nitrogen
8 O Oxygen
9 F Fluorine
10 Ne Neon
Now to the Problem.
I am reading from the file.
Then Copying the text into an array of strings.
I then try to put it into a stringstream, parsing it into three parts and then using them as parameters to the function.
The program is working properly as I intended until line 63.
The problem is that for some reason Buffer remains empty, hence the Objects of Class Element remain empty.
Line 76 should return Fluorine, but there is no output.
I would appreciate all help.
NOTE: default.h contains the included header files, and the using std::something statements...
Judging from your code, you should at least be getting the atomic numbers correctly.
This: Buffer.str(""); clears the stringstream so, by your code, you would be getting empty symbol and element names. You should call Buffer.str(""); at the end of the loop.
Also, why are you reading 110 lines from the file and only outputting 109 elements? If it's because there's a blank line at the beginning of the file, then accessing Eleme[0] is accessing the blank line. You should read over the blank line, and put the rest into the Eleme array.
You suggestion worked! Thanks a lot!!
And yes I noticed that I was assigning B to both Element and symbol Name when I made the previous post (while debugging that was)!