Getting ifstream from istream and calling functions via overloaded >> operator - function

I've created an object, PDBParser, to extract information from a PDB file. Now I am trying to overload the >> and << operators so that I can use them from the main as so:
inFile >> MyPDBParser;
outfile << MyPDBParser;
I've got the << operator all set, but I can't seem to get the >> operator to work properly.
Here is the .h file for the PDBParser class to give you a better idea of what's going on:
#include <iostream>
#include <cstdlib>
#include "FloatArray.h"
#include "IntArray.h"
#include "Atom.h"
#include "AtomArray.h"
using namespace std;
class PDBParser
{
friend ostream& operator<<(ostream& _ostream, PDBParser &rhs);
friend istream& operator>>(istream& _istream, PDBParser &rhs);
public:
PDBParser();
PDBParser(string atom1, string atom2, int separation);
PDBParser(const PDBParser& orig);
virtual ~PDBParser();
void grabAtoms(ifstream &infile);
void findAtoms();
void setAtom1(string rhs);
void setAtom2(string rhs);
void setSeparation(int rhs);
string getAtom1();
string getAtom2();
int getSeparation();
private:
string atom1s;
string atom2s;
int separation;
AtomArray *atoms1;
AtomArray *atoms2;
AtomArray *matches1;
AtomArray *matches2;
FloatArray *x1;
FloatArray *y1;
FloatArray *z1;
FloatArray *x2;
FloatArray *y2;
FloatArray *z2;
IntArray *allsequence;
ifstream backupinfile;
void trim(string &rhs);
void incrementArrays(int newElements);
};
Essentially what I need the >> operator to do is get the infile from the istream and then call the grabAtoms(infile) and findAtoms() functions for this instance of the PDBParser object.
Here's what I have now, which doesn't work. Please forgive the commented lines, as they were things I was attempting to make work. I tried adding the backupinfile object to the PDBParser class just to make things work, so normally it didn't have this and doesn't use it.
istream & operator>>(istream & _istream, PDBParser &rhs)
{
// ifstream in;
// _istream >> rhs.grabAtoms(in) >> rhs.findAtoms();
_istream >> rhs.backupinfile;
rhs.grabAtoms(rhs.backupinfile);
rhs.findAtoms();
return _istream;
}
I've established that the issue here is that my function needs to receive an ifstream object and I can't figure out how to get that from the istream object.
Here's my working << overload just for the heck of it:
ostream & operator<<(ostream & _ostream, PDBParser &rhs)
{
for(int i=0; i < rhs.x1->getSize(); i++)
{
_ostream.precision(3);
_ostream << fixed;
_ostream << setprecision (3) << rhs.x1->get(i) << " ";
_ostream << setprecision (3) << rhs.y1->get(i) << " ";
_ostream << setprecision (3) << rhs.z1->get(i) << " ";
_ostream << setprecision (3) << rhs.x2->get(i) << " ";
_ostream << setprecision (3) << rhs.y2->get(i) << " ";
_ostream << setprecision (3) << rhs.z2->get(i) << endl;
}
return _ostream;
}
Thanks

Related

Maximum value of thrust device_vector

i am trying to find the maximum value and it's location of a thrust::device_vecotr.
the mechanism below can save the position of the maximum value, however, i couldn't find the max_val.
i have cout statements to track the running order and where it crashes. it seems to be it crash on this line
int max_val = *iter;
it shows this result:
terminate called after throwing an instance of 'thrust::system::system_error'
what(): invalid argument
1234567
here is the code
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
int main()
{
std::cout<<"1";
thrust::host_vector<int>h_vec(5);
h_vec.push_back(10);
h_vec.push_back(11);
h_vec.push_back(12);
h_vec.push_back(13);
h_vec.push_back(14);
std::cout<<"2";
thrust::device_vector<int>d_vec(5);
std::cout<<"3";
thrust::copy_n(h_vec.begin(),5,d_vec.begin());
std::cout<<"4";
// print_vector("D_Vec",d_vec);
std::cout<<"5";
thrust::device_vector<int>::iterator iter=thrust::max(d_vec.begin(),d_vec.end());
std::cout<<"6";
unsigned int position = iter - d_vec.begin();
std::cout<<"7";
int max_val = *iter;
std::cout<<"8";
std::cout<<"Max Val= "<<14<<" #"<<position<< std::endl;
return 0;
}
Help .. please. also, if there is a better way to extract the maximum value and its position in device_vector using THRUST library it is more than appreciated.
You're not using vectors correctly. push_back() adds an element onto the end of an existing vector. It's clear that you want to replace existing elements.
Also, the thrust algorithm you want is thrust::max_element, not thrust::max
Here's a fully worked code with those issues fixed:
$ cat t1229.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
int main()
{
std::cout<<"1" <<std::endl;
thrust::host_vector<int>h_vec(5);
h_vec[0] = 10;
h_vec[1] = 11;
h_vec[2] = 12;
h_vec[3] = 13;
h_vec[4] = 14;
std::cout<<"2" << std::endl;
thrust::device_vector<int>d_vec(5);
std::cout<<"3" << std::endl;
thrust::copy_n(h_vec.begin(),5,d_vec.begin());
std::cout<<"4" << std::endl;
// print_vector("D_Vec",d_vec);
std::cout<<"5" << std::endl;
thrust::device_vector<int>::iterator iter=thrust::max_element(d_vec.begin(),d_vec.end());
std::cout<<"6" << std::endl;
unsigned int position = iter - d_vec.begin();
std::cout<<"7" << std::endl;
int max_val = d_vec[position];
std::cout<<"8" << std::endl;
std::cout<<"Max Val= "<<max_val<<" #"<<position<< std::endl;
return 0;
}
$ nvcc -o t1229 t1229.cu
$ ./t1229
1
2
3
4
5
6
7
8
Max Val= 14 #4
$

std::for_each and std::vector destructor call

I have the following problem with std::for_each and a functor proxy object.
See the following code:
struct Functor {
std::vector<int> data;
const unsigned mID;
static unsigned id;
Functor() : mID(id++) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}
~Functor() {
std::cout << "Functor dtor: " << mID << std::endl;
}
void operator() (int i) {
std::cout << "Functor print: " << i << std::endl;
data.push_back(i);
std::cout << "Dump: ";
for(int i = 0; i < data.size(); ++i)
std::cout << data[i] << " ";
std::cout << std::endl;
}
};
unsigned Functor::id = 0;
From above, the proxy object simply does 2 things, it prints the data out to the CMD and it stores a copy for itself to use. Below is the example use case of the object:
int main () {
std::vector<int> intvec;
for(int i = 0; i < 10; ++i)
intvec.push_back(i);
Functor myfunctor;
std::for_each(intvec.begin(), intvec.end(), myfunctor);
std::cout << "Data in my functor: " << myfunctor.data.size() << std::endl;
for(int i = 0; i < myfunctor.data.size(); ++i)
std::cout << "myfunctor data: " << myfunctor.data[i] << std::endl;
return 0;
}
This is the part it gets really fishy for me. The output generated is that my functor proxy object is constructed once but deconstructed three times! Something is bypassing the construction call.
Also as a result of the destructor being called at the end of the std::for_each, the Functor.data is empty as well!
Is there a way to make sure data inside Functor is kept persistent? I wish to keep track of the state of my functor when used inside functions such as std::for_each (Basically any given std algorithm function that can take in a unary functor)
Do note that I am using c++03 ONLY. Many thanks.
[...] my functor proxy object is constructed once but deconstructed three times! Something is bypassing the construction call.
Not quite. Your class is default-constructed once, but is also copy-constructed twice. You don't log the copy construction, so it doesn't show up on your output.
If you add a logging copy constructor, you'll see "Functor constructed with id: 0" printed three times:
Functor(const Functor& other) : mID(other.mID) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}

C++ to HTML conversion using namespaces

I'm trying to convert a .cpp file into a .html file.
Basically, at the end of the program, the html file when opened on chrome or whatever should look exactly like:
#include <iostream>
using namespace std;
int main()
{
int x = 4;
if (x < 3) x++;
cout << x << endl;
return 0;
}
I have three files, Source.cpp, fileToConvert.cpp, fileConverted.htm.
Source.cpp:
//This program will convert the selected file to another file for example .cpp to .html file.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void conversion(ifstream& inStream, ofstream& outStream);
int main()
{
ifstream fin;
ofstream fout;
cout << "Begin editing files.\n";
fin.open("fileToConvert.cpp"); //input file (must in the same folder)
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("fileConverted.htm"); //output file (in the same folder)
if (fout.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
fout << "<PRE>" << endl; //<PRE> is the tag for HTML file that will convert all the spacing according to the input file
addPlusPlus(fin, fout);
fout << "</PRE>" << endl; //</PRE> is the tag for HTML file that will close the <PRE> tag
fin.close();
fout.close();
cout << "End of editing files.\n";
return 0;
}
void conversion(ifstream& inStream, ofstream& outStream)
{
char next;
inStream.get(next);
while (!inStream.eof())
{
if (next == '<')
outStream << "<";
else if (next == '>')
outStream << ">";
else
outStream << next;
inStream.get(next);
}
}
fileToConvert.cpp:
#include <iostream>
using namespace std;
int main()
{
int x = 4;
if (x < 3) x++;
cout << x << endl;
return 0;
}
And then the output should look like the first block of code above as said in HTML format.
The only way I can get this to work is to place the main() method in fileToConvert.cpp inside of a namespace, like so:
#include <iostream>
using namespace std;
namespace secondMain{
int main()
{
int x = 4;
if (x<3) x++;
cout << x << endl;
return 0;
}
}
Problem obviously being, this will display the namespace secondMain{...} code inside of the .htm file and, which I do not want.
If I don't use this second namespace, obviously the program will not work since there are two main() methods defined.
What am I missing in this program? The only workaround I found was adding that second namespace, and I do have to use namespaces in this project, but cannot display that namespace definition in the html page.
Any information is appreciated,
Thanks!!
If I understand correctly, the problem might be that you are compiling fileToConvert.cpp along with Source.cpp.

getline() no instance of overloaded function c++

trying to code a cin.getline function and it throws me an error saying theres no instance of overloaded function? I'm sure im using the parameters correctly, not sure how to fix..
#include <iostream>
#include <string>
#include <ctime>
#include <string>
#include <cstring>
#include "NonPerishable.h"
#include "Item.h"
using namespace std;
namespace sict {
class NonPerishable : public Item{
fstream& save(std::fstream& file) const {
file << "N," << sku() << "," << name() << "," << cost() << "," << taxed() << "," << quantity() << endl;
return file;
}
fstream& load(std::fstream& file) {
char sku1[15];
cin.ignore(2);
cin.getline(sku1, 15, ',');
//edit:
double integer;
cin.getline(integer, 15, ',');
}
ostream& write(std::ostream& os, bool linear) const {
}
istream& read(std::istream& is) {
}
fstream& save(std::fstream& file){
}
};
}
any help would be appreciated !
Edit: i fixed it for retrieving chars, but doubles/int wont work?
The third argument is supposed to be a char, so try single quotes:
cin.getline(sku1, 15, ',');

Best way to separate parallel MPI part in sequential program

I've have a huge sequntial program, in which I want to parallelize some algo with MPI and CUDA. How correctly separate sequential part from parallel? The problem lies in nesting of parallel algo, and using of slurm or loadLeveler as well(e.g. on my MPI cluster I can't write something like: mpirun -n 1 a.out: -n 2 b.out).
Example:
int main()
{
funcA();
}
void funcA()
{
funcB();
}
void funcB()
{
parallel algo starts here....
}
I've found a great solution, for this problem. This is sample code:
#include <iostream>
#include <mpi.h>
#include <unistd.h>
using namespace std;
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int r;
MPI_Comm_rank(MPI_COMM_WORLD, &r);
if (r == 0) {
cout << "[GUI]Start perfoming initialization...." << endl;
sleep(2);
cout << "[GUI]Send command to start execution...." << endl;
int command = 1;
//TODO: now it's hardcoded to send data to 1 proc
MPI_Send(&command, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
cout << "[GUI]Waiting for execution results..." << endl;
int buf[5];
MPI_Recv(&buf, 5, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
for (int i=0; i<5; i++)
{
cout << "buf["<< i << "] = " << buf[i] << endl;
}
} else {
int command;
MPI_Recv(&command, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
cout << "Received command: " << command << endl;
if (command == 1) {
cout << "[ALGO]Receive command to start execution" << endl;
sleep(2);
cout << "[ALGO]Send computed data..." << endl;
int buf[5] = {5,4,3,2,1};
MPI_Send(&buf, 5, MPI_INT, 0, 0, MPI_COMM_WORLD);
}
}
MPI_Finalize();
return 0;
}