Several links errors in my project: LNK2019, LNK2005 - c++

I tried every solution for those errors in google, but found no answer for this problem.
The project is really big, but here is one of the files:
cpp file:
#include"Cluster.h"
Cluster::Cluster()
{}
Cluster::~Cluster() //close files and reomve dynamically-allocated memory
{
Splittedfile.close();
clustring.close();
Linefile.close();
delete[] protein;
delete[] NextProtein;
}
void spllitFile()
{
// check length of the file, and set length of NumOfSeq
Linefile.seekg(0, Linefile.end);
long sizeOfFile = Linefile.tellg();
NumOfProteins = sizeOfFile - 20;
//from the begining of LineFile:
//read 1 protein from LineFile & write it to Splittedfile.
//Each loop is advaced with:
// /n to Splittedfile & another 1 character "slide" in LineFile.
Linefile.seekg(ios_base::beg);
char* CopyProtein = new char[20]; // allocate buffer for reading 1 protein
long startPlaceOfRead = 0;
while (!(Linefile.eof()))
{
if ((startPlaceOfRead != 0) || (((sizeOfFile - startPlaceOfRead) < 20.0)))
Splittedfile << "\n";
Linefile.seekg(startPlaceOfRead);//to next protein - one for enter. one for back
if ((sizeOfFile - startPlaceOfRead) < 20.0) break;//if not enough for 1 protein
Linefile.read(CopyProtein, 20); // read 1 protein from infile
Splittedfile.write(CopyProtein, 20);// write to outfile
startPlaceOfRead++;
}
delete[] CopyProtein; // release dynamically-allocated memory
}
void buildClustrs()
{
Form Form;
char X[] = "XXXXXXXXXXXXXXXXXXXX‎‎‎‎««««««««";
int removed = 0;
for (int first = 0; first <= NumOfProteins; first++)//for the 1st
{
Splittedfile.seekg(0);
Splittedfile.seekg(first * 20 + 2 * first, ios_base::beg);
//int ThisPlace = Splittedfile.tellg();
Splittedfile.read(protein, 20);
if (strcmp(X, protein) == 0) continue; // 0= EQUAL
clustring << "\n\n\n";
clustring.write(protein, 20);
cout << "protein number " << first << " written as a lonely cluster " << endl; // WHEN FOUND belonging only-printing!
//remove this protein
Splittedfile.seekg(-20, Splittedfile.cur);
Splittedfile << "XXXXXXXXXXXXXXXXXXXX";
removed++;
for (int Allother = first + 1; Allother <= NumOfProteins; Allother++) //the following protein
{
Splittedfile.seekg(Allother * 20 + 2 * Allother);
Splittedfile.read(NextProtein, 20); // READ next protein, -read -go on automaticly-
if (strcmp(X, NextProtein) == 0) continue;
if ( (Form.Compare2Proteins (protein, NextProtein) ) !=-1)//>=60%
{
clustring << "\n";
clustring.write(NextProtein, 20);// write to clustring second protein in cluster
cout << "protein number " << Allother << " written to cluster " << first << endl; // WHEN FOUND belonging only-printing!
//remove this protein
Splittedfile.seekg(-20, Splittedfile.cur);//to next protein
Splittedfile << "XXXXXXXXXXXXXXXXXXXX";
removed++;
}
}
}
}
Header file:
#pragma once
#include <iostream>
#include <string.h>
#include <fstream>
#include <sstream>
#include <tchar.h>
#include <string.h>
#include "Main.h"
#include "Form.h"
using namespace std;
class Cluster
{
public:
Cluster();
~Cluster();
void spllitFile();
void buildClustrs();
};
Screenshot with the errors:

I add more headers files, it may assist, beacuse I see no one know where the problem exactly is. thank you.
form.h:
#pragma once
#include <string>
#include <tchar.h>
#include <string.h>
using namespace std;
char *formString[6] = { "111100", "111010", "101110", "110110", "111001", "110101" };
class Form
{
public:
Form();
~Form();
//void spllitBySizeOfForm(int sizeOfForm, char protein[20], int i);
int Compare2Proteins(char *protein1, char *Nextprotein);
char* stringXform(char str[6], char form[6]);
};
HashEntry.h:
#pragma once
#include <string>
#include <tchar.h>
#include <string.h>
using namespace std;
class HashEntry
{
public:
HashEntry(int key, int value);
int getValue();
int getKey();
};
HashMap.h:
#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <tchar.h>
#include <string.h>
#include "HashEntry.h"
using namespace std;
const int TABLE_SIZE = 20;
class HashMap
{
public:
HashMap::HashMap();//
HashMap::~HashMap();
int get(int key); // get value. for example: B--> get 0.
void put(int key, int value);//build entry AND put value in it.
void PutHmap(); // Put values to HashMap. get it by Hmap.get
};
main.h:
#pragma once
#include <iostream>
#include <string.h>
#include <fstream>
#include <sstream>
#include <tchar.h>
#include <string.h>
#include "Cluster.h"
using namespace std;
long NumOfProteins = 0;
char* protein = new char[20]; // allocate memory for file content
char* NextProtein = new char[20]; // allocate memory for file content
fstream Splittedfile;
fstream newClusering;
ofstream clustring;
ifstream Linefile;
class Main
{
public:
//void position(char form[6], char str[6])
};

Related

How to change the order of an array in c++

I am try to change the order of an array of char like this :
char arr_char[]="ABCDEFGHIJABCDEFGHIJ";
i used the rand() function in the following code :
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char arr_char[]="ABCDEFGHIJABCDEFGHIJ";
int arrSize=sizeof(arr_char)-1;
srand(time(0));
for(int i=0;i<20;i++)
{
cout<<arr_char[rand() % arrSize]<<" ";
}
}
but the rand function repeat some characters more than twice and i want to change the order of the array in which every characters repeat only twice not more .
This will probably suffice
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string arr_char = "ABCDEFGHIJABCDEFGHIJ";
random_shuffle(arr_char.begin(), arr_char.end());
cout << arr_char;
}

C++ function with pointer argument

I am writing a C++ program that outputs data to a file, generates a python script and calls pyplot to make the plotting.
However, when I pass the arguments in terms of the pointers, it can be compiled properly, but cannot run. It returns error. When I use Xcode debug mode and execute it step by step, it gives correct result by chance but not always. Sometimes it also returns an error.
I doubt that it might be caused by some memory allocation problem, but I cannot identify what is exactly the problem.
My codes are as following:
1) main
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include "PyCPlot.h"
using namespace std;
double pi = 3.1415926;
int main(int argc, const char * argv[]) {
int nline = 100;
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
for (int i=0; i<nline; i++){
np_list[i] = double(i)/double(nline)*2*pi;
pack_fraction_np[i] = cos(np_list[i]);
}
PyCPlot_data_fout("RandomPacking", nline, np_list, pack_fraction_np);
PyCPlot_pythonscript("RandomPacking", "Random Packing");
PyCPlot_pyplot("RandomPacking", "Random Packing");
return 0;
}
2) head file
#ifndef PyCPlot_h
#define PyCPlot_h
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int PyCPlot_data_fout(string datafilename, int nline, double * x, double *y){
ofstream fout;
fout.open(datafilename+".txt");
fout << nline << endl;
for (int i=0; i<nline; i++){
fout << x[i] << " " << y[i] << endl;
}
fout.close();
return 0;
}
int PyCPlot_pythonscript(string datafilename, string plttitle){
string strhead = "import numpy as np\nimport matplotlib.pyplot as plt\n";
string strpltfig = "plt.figure()\n";
string strpltplt = "plt.plot(xlist, ylist)\n";
string strplttit = "plt.title('"+plttitle+"')\n";
string strpltshw = "plt.show()\n";
string strfileopen ="f = open('"+datafilename+".txt', 'r')\n";
string strreadline ="size = map(int, f.readline().split())\n";
string strpltlist ="xlist = np.zeros((size))\nylist = np.zeros((size))\n";
string strfor = "for i in range(size[0]):\n xlist[i], ylist[i] = map(float, f.readline().split())\n";
ofstream pyout;
pyout.open("PyCPlot_"+datafilename+".py");
pyout << strhead << strfileopen << strreadline << strpltlist << strfor;
pyout << strpltfig << strpltplt << strplttit << strpltshw;
pyout.close();
return 0;
}
int PyCPlot_pyplot(string datafilename, string plttitle){
string strsystemsh ="source ~/.bashrc; python PyCPlot_"+datafilename+".py";
system(strsystemsh.c_str());
return 0;
}
#endif /* PyCPlot_h */
When it is ran, I get below error message
malloc: *** error for object 0x1002002e8: incorrect checksum for freed object - object was probably modified after being freed.
You want to pass an array, so pass an actual array which can be sized at runtime (std::vector), not some random pointer that hopefully will be pointing to the first element of an array (and in this case, it doesn't)
Your mistake is using new double(x) instead of new double[x]. The former allocates a single double with a value equal to x, and the latter allocates an array of double of size x and returns a pointer to the first element, but, as I've said, you wouldn't have that problem at all had you actually used std::vector and not dabbled with pointers like the early 90s style (not to mention, you wouldn't have a memory leak had you used std::vector).
You're doing a few things which are not right or seem strange.
The code new double(nline) will allocate a single double with the value of nline, which doesn't seem what you intend.
It looks like you intend to dynamically allocate an array of double. Actually from the code you've shown there's no reason you can't do a simple array as the size is known at compile time.
This code below:
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
Could be replaced with:
double np_list[nline];
double pack_fraction_np[nline];
The following lines allocate a single double for np_list and pack_fraction_np:
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
As a result, when you will enter your loop, you will write data to invalid memory blocks. You have to use square brackets to define an array (I do not get any error; using clang++).
Consider to use the std::vectorclass. Here is an example (your example) with std::pair of double nested in a std::vector:
PyCPlot.h
#ifndef PyCPlot_h
#define PyCPlot_h
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <utility>
using namespace std;
int PyCPlot_data_fout(string datafilename, std::vector<std::pair<double, double>>& v){
ofstream fout;
fout.open(datafilename+".txt");
fout << v.size() << endl;
for (int i=0; i < v.size(); i++){
fout << v[i].first << " " << v[i].second << endl;
}
fout.close();
return 0;
}
int PyCPlot_pythonscript(string datafilename, string plttitle){
string strhead = "import numpy as np\nimport matplotlib.pyplot as plt\n";
string strpltfig = "plt.figure()\n";
string strpltplt = "plt.plot(xlist, ylist)\n";
string strplttit = "plt.title('"+plttitle+"')\n";
string strpltshw = "plt.show()\n";
string strfileopen ="f = open('"+datafilename+".txt', 'r')\n";
string strreadline ="size = map(int, f.readline().split())\n";
string strpltlist ="xlist = np.zeros((size))\nylist = np.zeros((size))\n";
string strfor = "for i in range(size[0]):\n xlist[i], ylist[i] = map(float, f.readline().split())\n";
ofstream pyout;
pyout.open("PyCPlot_"+datafilename+".py");
pyout << strhead << strfileopen << strreadline << strpltlist << strfor;
pyout << strpltfig << strpltplt << strplttit << strpltshw;
pyout.close();
return 0;
}
int PyCPlot_pyplot(string datafilename, string plttitle){
string strsystemsh ="source ~/.bashrc; python PyCPlot_"+datafilename+".py";
system(strsystemsh.c_str());
return 0;
}
#endif /* PyCPlot_h */
PyCPlot.cpp
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include "PyCPlot.h"
using namespace std;
double pi = 3.1415926;
int main(int argc, const char * argv[]) {
int nline = 100;
std::vector<std::pair<double, double>> v;
v.reserve(nline);
double a;
for (int i=0; i < nline; i++){
a = double(i)/double(nline)*2*pi;
v.push_back(std::make_pair(a, cos(a)));
}
PyCPlot_data_fout("RandomPacking", v);
PyCPlot_pythonscript("RandomPacking", "Random Packing");
PyCPlot_pyplot("RandomPacking", "Random Packing");
return 0;
}

Segmentation Fault while Reading from File

I am trying to print last 10 lines of a file. Following is my code, but it is giving a segmentation fault due to fscanf. While running with gdb the fault reads : vfscanf.c: No such file or directory.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
FILE *fp = fopen("microfile.txt","r");
char *c[10];
int idx = 0;
cout<<fp<<"\n";
while(!feof(fp))
{
if(idx<10)
{
fscanf(fp,"%s",c[idx]);
idx++;
}
else if(idx==10)
{
for(int i=0;i<idx-1;i++)
{
c[i] = c[i+1];
}
fscanf(fp,"%s",c[idx-1]);
}
}
int i=0;
while(i<10)
{
cout<<c[i]<<"\n";
i++;
}
}
The source of the problem comes from the fact you have an array of pointers on this line:
char* c[10];
And later on in the program you attempt to assign character values to these pointers. Maybe you meant for just an array of characters instead:
char c[10];
Moreover, use of the Standard library is recommended. Try using std::string and standard streams and your program can be made more maintainable:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string s;
s.assign(
std::istreambuf_iterator<char>(std::ifsteam("microfile.txt").rdbuf()),
std::istreambuf_iterator<char>());
for (char c : s)
std::cout << c << std::endl;
}

String assignment error

I am writing an ns3 application, for which I need to write a vector to a file, read the file to construct the vector back again and pick random elements from the vector. This is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/mf-helper.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
#include "ns3/data-rate.h"
#include "ns3/mobility-module.h"
#include "ns3/wifi-module.h"
#include "ns3/ideal-wifi-manager.h"
#include "ns3/wifi-remote-station-manager.h"
#include "ns3/wifi-mode.h"
using namespace ns3;
using namespace std;
void writeFile(string, vector<string>);
void readFile(string, vector<string> &);
unsigned int Random(int,int);
bool Find(vector<string> , string);
void selectNodes(vector<string>);
vector<string> senders;
int main(int argc, char **argv)
{
vector<string> vect;
vect.push_back("10.1.1.1");
vect.push_back("10.1.1.2");
vect.push_back("10.1.1.3");
vect.push_back("10.1.1.4");
vect.push_back("10.1.1.5");
vect.push_back("10.1.1.6");
vect.push_back("10.1.1.7");
writeFile("data.txt", vect);
vector<string> ret;
readFile("data.txt",ret);
selectNodes(ret);
}
void writeFile(string name, vector<string> vs)
{
ofstream outfile(name.c_str(), ios::out);
ostream_iterator<string> oi(outfile, "\n");
copy(vs.begin(), vs.end(), oi);
}
void readFile(string name, vector<string> &vect)
{
ifstream file(name.c_str());
copy(istream_iterator<string> (file), istream_iterator<string>(), back_inserter(vect));
}
void selectNodes(vector<string> ret)
{
srand(time(NULL));
string src;
string dest;
unsigned int s= ret.size();
src = ret[Random(1,s)];
dest = ret[Random(1,s)];
while(Find(senders, src))
{
src = ret[Random(1,s)];
}
while (src == dest)
{
src = ret[Random(1,s)];
if (dest != src)
break;
}
cout << "##Source: " << src << std::endl;
cout << "##Destination: " << dest << std::endl;
senders.push_back(src);
}
unsigned int Random(int nLow, int nHigh)
{
return (rand() % (nHigh - nLow + 1)) + nLow;
}
bool Find(vector<string> senders, string addr)
{
for(unsigned int i=0;i<senders.size();i++)
if(senders[i] == addr)
return 1;
return 0;
}
This code crashes randomly. This is what gdb says
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xfffffffffffffff8
0x00007fff8ad5a220 in std::string::_Rep::_M_grab ()
(gdb) bt
#0 0x00007fff8ad5a220 in std::string::_Rep::_M_grab ()
#1 0x00007fff8ad5a29b in std::string::assign ()
#2 0x0000000100002a31 in selectNodes (ret=#0x7fff5fbff7c0) at test_write.cc:74
#3 0x0000000100003cf5 in main (argc=1, argv=0x7fff5fbff998) at test_write.cc:49
Why is the string assignment failing? I found that some people had this porblem due to memory leaks. But that does not seem the case here. Am I missing something?
There is problem with these lines:
src = ret[Random(1,s)];
dest = ret[Random(1,s)];
because the value Random returns could be equal to s which is out of range. The maxim value of index to ret is s-1.
So the solution is, either you write this:
src = ret[Random(1,s-1)];
dest = ret[Random(1,s-1)];
Or, define Random as:
unsigned int Random(int nLow, int nHigh)
{
return (rand() % (nHigh - nLow + 1)) + nLow - 1;
}
I would suggest you to redine the Random as suggested above, because it is mathematically sound to say that Random generates a value which falls in the range [nLow, nHigh). Dikkstra has provided a sound argument for this. Read this:
Why numbering should start at zero
By the way, you should accept vector argument by reference.
I would say that the problem is you access your vector with illegal indexes. A vector has an index from 0 to size-1, just like any other C and C++ array. Change your Random calls to Random(0, s - 1).

boost filename extension with multiple "."

I have filenames like this : 09.04.201115_09_ch_4.txt
I would like to extract the filestem only. I tried using boost filesystem path, but it has problems with the multiple dots in the filename. (I didn't come up with the naming).
Is there a way around that? Can I get only the filename without the extension? My code looks like this:
std::string stringtmp = path.parent_path().string() +"/"+path.stem().string()+".png" ;
Ok here's the code (it's using the ROOT framework):
#include "TH1F.h"
#include "TH2F.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TCanvas.h"
#include "TVirtualFitter.h"
#include "TMath.h"
#include "TGraph.h"
#include <fstream>
#include <iostream>
#include "TApplication.h"
#include "TImage.h"
#include <string>
#include <sstream>
#include "TStyle.h"
#include "TROOT.h"
#include "TGraph2D.h"
#include "boost/filesystem.hpp"
Int_t npeaks = 10;
Double_t fpeaks(Double_t *x, Double_t *par) {
Double_t result = par[0] + par[1]*x[0];
for (Int_t p=0;p<npeaks;p++) {
Double_t norm = par[3*p+2];
Double_t mean = par[3*p+3];
Double_t sigma = par[3*p+4];
result += norm*TMath::Gaus(x[0],mean,sigma);
}
return result;
}
void graph(std::string name, bool big){
Float_t x[5001],y[5001];
std::ifstream in;
TCanvas *c1 = new TCanvas("c1","c1",10,10,1000,500);
if(!big){
in.open(name.c_str());
for(Int_t i = 0 ; i< 5001 ;i++){
in >> x[i] >> y[i];
}
c1->cd(1);
TGraph *gr = new TGraph(5001,x,y);
gr->SetMinimum(-60.);
//gr->GetYAxis()->SetMinimum(-70.);
// gr->GetYAxis()->SetTitle("dB");
gr->Draw("A*");
TH1F *h = gr->GetHistogram();
for(Int_t i = 0 ; i< 5001 ;i++){
if(y[i]>= -60.)
h->SetBinContent(i,y[i]);
}
//c1->cd(2);
h->SetYTitle("Intensity in dB");
h->SetXTitle("#lambda in nm");
h->SetTitle("Sectrum");
h->Draw();
TSpectrum *s = new TSpectrum(1000);
Int_t nfound = s->Search(h,1,"new");
std::cout <<"Found " << nfound << " candiate peaks to fit\n";
c1->Update();
//estimate linear background
Double_t par[3000];
TF1 *fline = new TF1("fline","pol1",842,852);
h->Fit("fline","qn");
//c1->cd(2);
par[0] = fline->GetParameter(0);
par[1] = fline->GetParameter(1);
//loop on all found peaks. Eliminate peaks at the background level
Float_t *xpeaks = s->GetPositionX();
for (Int_t p=0;p<nfound;p++) {
Float_t xp = xpeaks[p];
Int_t bin = h->GetXaxis()->FindBin(xp);
Float_t yp = h->GetBinContent(bin);
if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue;
par[3*npeaks+2] = yp;
par[3*npeaks+3] = xp;
par[3*npeaks+4] = 3;
npeaks++;
}
c1->Update();
TImage *img = TImage::Create();
img->FromPad(c1);
std::stringstream _name;
_name << name << ".png";
_name >> name;
boost::filesystem::path path(name);
std::string stringtmp = path.parent_path().string() +"/"+path.stem().string()+".png" ;
std::cout <<"\n \n stem \n \n"<<stringtmp<< '\t' << path.stem().string() << std::endl;
img->WriteImage(stringtmp.c_str());
return;
}
The output looks like this:
Warning in : Deleting canvas with same name: c1
Found 39 candiate peaks to fit
stem
29/12.04.201115_09_ch_4.txt.png 12.04.201115_09_ch_4.txt
This works for me:
#include <ostream>
#include <iostream>
#include <boost/filesystem.hpp>
int main()
{
boost::filesystem::path const p("C:\\Code\\09.04.201115_09_ch_4.txt");
// prints "C:\Code\09.04.201115_09_ch_4.txt"
std::cout << p << '\n';
// prints "09.04.201115_09_ch_4.txt"
std::cout << p.filename() << '\n';
// prints "09.04.201115_09_ch_4"
std::cout << p.stem() << std::endl;
}
So, essentially all you need is p.stem(); if that doesn't work for you, you'll need to post a compilable repro.