fstream only reading integers - c++

My code works fine when the file Im reading from only contains ints, but when I have floats in the file it doesnt seem to work, for example if I have 1.5 in the file it will only read it as 1 and it wont read any of the numbers after it.
Anyone knows whats causing this? The dynamic array where everything is saved in is a float so Im not sure what to do at this point
#include <iostream>
#include <fstream>
#include <string>
float *allocateArray(std::string fileName, int &arraySize, int &counter)
{
int a = 0;
std::ifstream myReadFile;
myReadFile.open(fileName);
float *arr = new float[arraySize]{0.0};
while (myReadFile >> a)
{
counter++;
if(counter == arraySize)
{
arr[arraySize -1] = a;
}
else
{
float *tempArray = new float[arraySize +1]{0.0};
for(int i = 0; i < arraySize; i++)
{
tempArray[i] = arr[i];
}
delete[] arr;
arraySize++;
arr = new float[arraySize];
for(int x = 0; x < arraySize; x++)
{
arr[x] = tempArray[x];
}
arr[arraySize-1] = a;
}
}
myReadFile.close();
return arr;
}
void output(float *arr, int arraySize,int counter)
{
float sum = 0.0;
for(int x = 0; x < arraySize; x++)
{
sum += arr[x];
}
float average = sum/counter;
std::cout << "Output: ";
for(int i = 0; i < arraySize; i++)
{
if(arr[i] > average)
{
std::cout << arr[i] << " ";
}
}
}
int main()
{
int arraySize = 1;
int counter = 0;
float *arr = allocateArray("input.in", arraySize, counter);
std::cout << "Input: ";
for(int x = 0; x < arraySize; x++)
{
std::cout << arr[x] << " ";
}
output(arr, arraySize, counter);
getchar();
return 0;
}

Related

Sorting a list with indexes of another

I am trying to sort a list of indexes based on a list of string, and I receive bellow error - Segmentation fault. I cannot understand why I receive this error and how to solve it?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int size = 5;
char* mass[size];
int num[size];
for(int i = 0; i < size; i++) {
mass[i] = new char[20];
num[i] = i;
cin >> mass[i];
}
for(int i = 0; i < size; i++){
for(int j = size; j > i; j--)
if(strcmp(mass[num[j-1]], mass[num[j]]) > 0){
int tmp = num[j-1];
num[j-1] = num[j];
num[j] = tmp;
}
}
for(int i = 0; i < size; i++){
cout << mass[num[i]] << ", ";
}
return 0;
}
In the inner loop you start with j = size and then num[j] is an out-of-bounds array access.
In modern C++ you would solve this like this:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
const int size = 5;
std::array<std::string, size> mass;
std::array<int, size> num;
for (int i = 0; i < size; i++) {
std::cin >> mass[i];
num[i] = i;
}
std::ranges::sort(num, [mass](int a, int b) { return mass[a] <= mass[b];});
for(int i = 0; i < size; i++){
std::cout << mass[num[i]] << ", ";
}
std::cout << std::endl;
return 0;
}

Sequence Alignment problem using Pthreads

I am trying to implement Sequence alignment problem (Needleman-Wunsch algorithm) using p-Threads. I am confused how to map the concept of multi threading in this particular serial problem. The code of serial computation of sequence alignment is enclosed below.(Just Matrix calculation part)
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
class Matrix
{
private:
int x;
int y;
int** mat;
string gene1;
string gene2;
int match_penalty;
int mismatch_penalty;
int gap_penalty;
int minimum_penalty;
public:
Matrix(int gene1Len, int gene2Len)
{
x = gene2Len + 1; //gene2 length
y = gene1Len + 1; //gene 1 length;
mat = new int* [x];
for (int i = 0; i < x; i++)
mat[i] = new int[y];
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
mat[i][j] = 0;
}
}
//Default Penalties
match_penalty = 1;
mismatch_penalty = 3;
gap_penalty = 2;
minimum_penalty=0;
}
void Print_Matrix()
{
cout<<"\n";
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cout << mat[i][j] << "\t";
}
cout << "\n";
}
}
void setGenes(string gene1, string gene2)
{
this->gene1 = gene1;
this->gene2 = gene2;
}
void setPenalty(int mismatch, int gp,int match)
{
mismatch_penalty = mismatch;
gap_penalty = gp;
match_penalty=match;
}
void setMatrix()
{
//1st row and 1st Column values
for (int i = 0; i < x; i++)
{
mat[i][0] = i * gap_penalty;
}
for (int i = 0; i < y; i++)
{
mat[0][i] = i * gap_penalty;
}
// Other matrix values
for (int i = 1; i < x; i++)
{
for (int j = 1; j < y; j++)
{
if (gene1[j - 1] == gene2[i - 1]) //Similar gene values (A==A ||T==T)
{
mat[i][j] = mat[i - 1][j - 1]+match_penalty;
}
else
{
mat[i][j] = max({ mat[i - 1][j - 1] + mismatch_penalty , mat[i - 1][j] + gap_penalty, mat[i][j - 1] + gap_penalty });
}
}
}
}
};
int main()
{
string gene1 = "ACCA";
string gene2 = "CCA";
int matchPenalty;
int misMatchPenalty ;
int gapPenalty ;
cout<<"Enter the value of Match Penalty" << endl;
cin >> matchPenalty;
cout<<"Enter the value of misMatchPenalty Penalty" << endl;
cin >> misMatchPenalty;
cout<<"Enter the value of gapPenalty Penalty" << endl;
cin >> gapPenalty;
Matrix dp(gene1.length(), gene2.length());
dp.setGenes(gene1, gene2);
dp.setPenalty(misMatchPenalty, gapPenalty,matchPenalty);
dp.setMatrix();
dp.Print_Matrix();
}
How can I implement the above problem in P-threads? So far, I have used two threads to calculate matrix values of 1st column and 1st row simultaneously.But I have no idea how to compute all values of matrix in parallel. Kindly see my source code:
#include<string>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<pthread.h>
using namespace std;
//Global variables --shared by all threads
int matchPenalty;
int misMatchPenalty;
int gapPenalty;
struct gene_struct {
string gene1;
string gene2;
int rowSize;
int colSize;
int **mat;
};
void* set_matrix_row(void *args)
{
struct gene_struct *shared_block = (struct gene_struct *) args;
for (int i = 0; i < shared_block->rowSize; i++)
{
shared_block->mat[i][0] = i * gapPenalty;
}
return NULL;
}
void *set_matrix_column(void *args)
{
struct gene_struct *shared_block = (struct gene_struct *) args;
for (int i = 0; i < shared_block->colSize; i++)
{
shared_block->mat[0][i] = i * gapPenalty;
}
return NULL;
}
void set_Matrix_Diagnol(struct gene_struct shared_block)
{
//How Should I calculate rest of the matrix values using Pthreads?
}
void Print_Matrix(struct gene_struct shared_block)
{
cout<<"\n";
for (int i = 0; i < shared_block.rowSize; i++)
{
for (int j = 0; j < shared_block.colSize; j++)
{
cout << shared_block.mat[i][j] << "\t";
}
cout << "\n";
}
}
int main()
{
pthread_t ptid1, ptid2;
string gene1, gene2;
struct gene_struct shared_block;
cout << "Enter First Gene : ";
cin >> gene1;
cout << "Enter Second Gene : ";
cin >> gene2;
cout<<"Enter the value of Match Penalty" << endl;
cin >> matchPenalty;
cout<<"Enter the value of misMatchPenalty Penalty" << endl;
cin >> misMatchPenalty;
cout<<"Enter the value of gapPenalty Penalty" << endl;
cin >> gapPenalty;
shared_block.gene1 = gene1;
shared_block.gene2 = gene2;
shared_block.rowSize = gene2.length()+1;
shared_block.colSize = gene1.length()+1;
shared_block.mat = new int* [shared_block.rowSize]; //col = gene2+1
for (int i = 0; i < shared_block.rowSize; i++)
{
shared_block.mat[i] = new int[shared_block.colSize];
}
pthread_create(&ptid1, NULL, &set_matrix_row, (void *)&shared_block);
pthread_create(&ptid2, NULL ,&set_matrix_column, (void *)&shared_block);
pthread_join(ptid1,NULL);
pthread_join(ptid2,NULL);
Print_Matrix(shared_block);
}

Dijkstra's alghoritm with OpenMP

There is a fully working Dijkstra algorithm that takes values ​​from a file (or writes a new one) and writes data to a matrix. How can you improve the program using OpenMP so that its speed is significantly increased? New to openMP, had little experience with common matrices, mostly parallelization "for".
I attach all the code below:
#include <iostream>
#include <fstream>
#include <string>
#include <climits>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <locale.h>
#include <chrono>
using namespace std;
class Timer
{
private:
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
chrono::time_point<clock_t> m_beg;
public:
Timer() : m_beg(clock_t::now())
{
}
double elapsed() const
{
return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
}
};
void fillingArray(int** arr, int c, string filename) {
ofstream fout(filename);
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < c; i++){
for (int j = 0; j < c; j++) {
arr[i][j] = arr[j][i] = rand() % 10 + 1;
}
}
for (int i = 0; i < c; i++) {
fout << endl;
for (int j = 0; j < c; j++) {
fout << setw(5) << arr[i][j];
}
}
}
void read(int** arr, int c, string filename) {
char answer;
ifstream file;
file.open(filename);
if (!file) {
fillingArray(arr, c, filename);
}
else {
cout << "File found\nWant to overwrite it? (y / n)\n";
cin >> answer;
if (answer == 'y' || answer == 'Y') {
fillingArray(arr, c, filename);
}
else {
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
file >> arr[i][j];
}
}
}
}
file.close();
}
void Dijkstra(int** arr, int c, int st)
{
Timer t;
int count, index, i, u, m = st + 1;
int* distance = (int*)malloc(c * sizeof(int*));
bool* visited = new bool[c];
for (i = 0; i < c; i++)
{
distance[i] = INT_MAX; visited[i] = false;
}
distance[st] = 0;
for (count = 0; count < c - 1; count++)
{
int min = INT_MAX;
for (i = 0; i < c; i++)
if (!visited[i] && distance[i] <= min)
{
min = distance[i]; index = i;
}
u = index;
visited[u] = true;
for (i = 0; i < c; i++)
if (!visited[i] && arr[u][i] && distance[u] != INT_MAX &&
distance[u] + arr[u][i] < distance[i])
distance[i] = distance[u] + arr[u][i];
}
double time = t.elapsed();
cout << "Cost of the path from the initial peak to the rest:\t\n";
for (i = 0; i < c; i++) if (distance[i] != INT_MAX)
cout << m << " > " << i + 1 << " = " << distance[i] << endl;
else cout << m << " > " << i + 1 << " = " << "route not available" << endl;
cout << "Time passed: " << time << "с\n";
delete[] visited;
delete[] distance;
}
int main()
{
string filename, rash;
filename = "arr";
rash = ".dat";
int c;
cout << "Enter the number of ribs:\n";
cin >> c;
int** arr = (int**)malloc(c * sizeof(int*));
for (int i = 0; i < c; i++) {
arr[i] = (int*)malloc(c * sizeof(int));
}
filename += to_string(c) + rash;
read(arr, c, filename);
Dijkstra(arr, c, 0);
delete[] arr;
}

c++ program to print a horizontal bar chart

I want to print a chart by taking integers from console. I have come up with this syntax. Stuck at a conditional statement.
int main() {
int array[10];
int num;
int size = 0;
for(int i = 0; i < 10; i++)
{
cin >> num;
if(num == 0)
{
break;
}
array[i] = num;
size++;
}
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(*something goes here*)
cout << "*";
else
cout << " ";
}
cout << endl;
}
return 0;
}
Try this
#include <iostream>
using namespace std;
#define MAX 100
int main() {
int values[MAX];
int size = 0;
while (true) {
int num;
cin >> num;
if (num == 0) break;
else values[size++] = num;
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < values[i]; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}

Pointers Error, break in delete[] pointers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to C++ and i have a problem during the compilation of this code. I'm traslating it from another lenguage so i'm having doubts about how pointers works. I think that the error can be made by initializzation of pointers during the loop.
Anyway the aim of the code is: store the variable results and print it out after simulated data is elaborated. My data change size every loop so I've initialized arrays inside of the loop.
using namespace std;
int* Mwa(double price[], string data[], const int period, const int size)
{
double bandup;
double banddw;
int *index;
index = new int[size];
for(int i = 0; i < size; i++)
index[i]=1;
double cmP = size/period;
double cmp = floor(cmP);
double m;
double std;
for(int i = 0; i < period; i++)
{
m = 0;
std = 0;
for(int j = i*cmp; j < (i+1)*cmp - 1; j++)
{
m += price[j];
}
m = m/cmp;
for(int j = i*cmp; j < (i+1)*cmp - 1; j++)
{
std += pow(price[j] - m,2);
}
std = pow(std/cmp, 0.5);
bandup = m + NormalCDFInv(.95)*std; // aggiungere Z value in qlc modo
banddw = m - NormalCDFInv(.95)*std; // aggiungere Z value in qlc modo
for(int j = i*cmp; j < (i+1)*cmp - 1; j++)
{
if(price[j]> bandup)
index[j] = 0;
else if(price[j]< banddw)
index[j] = 0;
else
index[j] = 1;
}
}
return index;
}
///////////////////////////////////////////////////// MAIN /////////////////////////////////////////////////////////////////////
void main()
{
const int bdays = 251;
std::string f;
cout << "Insert the path of Real Dates to be used \n";
std::cin >> f;
if(f.size() < 5)
f = "H:/Bid-Ask/C++/Bid-Ask Project/Bid-Ask Project/DateReali.txt";
cout << "Insert the path of GTR Input Data to be used \n";
std::string path;
std::cin >> path;
if(path.size() < 5)
path = "H:/Bid-Ask/";
cout << "Insert an Integer number of simulations \n";
int sim;
std::cin >> sim;
double T = 1;
int dayC = 252;
double dt = T/dayC;
int expiry[15] = {1,2,3,4,5,6,7,8,9,10,12,15,20,30,50};
std::string name = " y.csv";
int period = 15;
const double sigmaeps = 0.051;
const double sigmaeta = 0.091;
double **results;
results = new double*[sim];
for(int i =0; i < 15; i++)
results[i] = new double[sim];
double *param;
for(int rnd = 0; rnd < sim; rnd++)
{
for(int e = 0; e < period; e++)
{
stringstream ss;
ss << expiry[e];
string exp = ss.str();
string line;
std::ifstream filein;
filein.open ((path) + exp + name);
if(filein.fail())
{
std::cout << "File opening error" << std::endl;
}
else
{
double *cleanprice;
string *cleandata;
string *cleantime;
int *price2;
double *series;
double *ret;
double *price;
string *data;
string *time;
int count = 0;
while(getline(filein,line))
{
count++;
}
filein.close();
int c = count-1;
data = new string[c];
time = new string[c];
price = new double[c];
cout << exp + "\t" << count << "\n";
filein.open (path + exp + name);
for(int i = 0; i<count; i++)
{
int cols;
if(i==0)
cols = 49;
else
cols = 47;
for(int j=0; j < cols; j++)
{
getline(filein,line,',');
if(i == 0)
continue;
if(j==2)
{
data[i-1] = line.substr(1,10);
time[i-1] = line.substr(12,8);
//cout << data[i-1] + "\t";
}
else if(j == 20)
{
std::istringstream stm;
stm.str(line.substr(1,line.length()));
stm >> price[i-1];
//price[i-1] = atof((line.substr(2,line.length())).c_str());
//cout << price[i-1] << "\n";
}
else
continue;
}
}
filein.close();
price2 = Mwa(price, data, period, c);
int newc = cumsumC(price2,c);
cleantime = new string[newc];
cleanprice = new double[newc];
cleandata = new string[newc];
int Ix = 0;
for(int i=0; i<c; i++)
{
if(price2[i] == 1)
{
cleanprice[Ix]=price[i];
cleantime[Ix] = time[i];
cleandata[Ix] = data[i];
Ix++;
}
}
//for(int i = 0; i < newc; i++)
//cout << cleanprice[i] << "\t" << cleandata[i] << "\t" << cleantime[i] << "\n";
ret = SimpleReturns(cleanprice, cleandata, cleantime, newc);
std::ofstream file;
file.open( f + "/Ret.txt",std::ios::out ) ;
for(int i = 0; i < newc; i++)
file << ret[i] << "\t" << cleanprice[i] << "\t" << cleandata[i] << std::endl;
file.close();
series = KalmanFiltering(f, sigmaeps, sigmaeta, ret, cleandata, newc);
std::ofstream file1;
file1.open(f + "/Kalman.txt",std::ios::out) ;
for(int i = 0; i < bdays; i++)
file1 << series[i] << "\n";
file1.close();
param = MA1(series, bdays);
double bps = pow(abs(param[0]),.5)*param[1]*100;
cout << param[0] << "\t" << param[1] << "\t" << bps << "\r\n";
results[e][rnd] = bps;
delete[] cleantime;
delete[] cleanprice;
delete[] cleandata;
delete[] time;
delete[] data;
delete[] price;
delete[] price2;
delete[] series;
delete[] ret;
}// Else in file reading
}// loop over expiries
}// loop over simulation
std::ofstream fileR;
fileR.open( path + "Results.txt", std::ios::out);
if(fileR.fail())
{
std::cout << "File opening error" << std::endl;
}
else
{
fileR << "Expiry" << endl;
for(int e = 0; e < 15; e++)
{
stringstream ss;
ss << expiry[e];
string exp = ss.str();
fileR << exp << " y" << "\t";
for(int rnd = 0; rnd < sim; rnd++)
{
fileR << results[e][rnd] << "\t";
}
fileR << endl;
}
}
fileR.close();
for(int i =0; i < 15; i++)
delete[] results[i];
delete[] param;
}
double* MA1(double ret[], const int sizeEr)
{
double *Param = new double[1];
int gran = 100;
double* grid;
double* gridV;
grid = new double[gran]; grid[0] = -1;
gridV = new double[gran]; gridV[0] = 0;
for(int i = 1; i < gran; i++)
{
grid[i] = grid[i-1]+.02;
gridV[i] = gridV[i-1]+ .005;
//cout << grid[i] << "\n";
}
double **F;
F = new double*[gran];
for(int i = 0; i < gran; i++)
F[i]= new double[gran];
for(int a = 0; a < gran; a++)
{
double GhostTerm = 0.0;
for(int i = 2; i< sizeEr; i++)
{
double c = 0;
for(int g = 0; g < i-1; g++)
c += pow((-grid[a]),g)*(ret[i-g]);
GhostTerm += pow(c,2);
}
for(int v = 0; v < gran; v++)
{
F[a][v] = -(sizeEr-1)*.5 *log(2*3.14159*pow(grid[v],2)) + (-.5)*GhostTerm/pow(grid[v],2);
}// loop on vola
}// loop on beta
double m = -gran;
int posB = 1;
int posV = 1;
for(int i = 1; i < gran; i++)
{ for(int j = 1; j < gran; j++)
{
if(abs(grid[i]) < .01)
continue;
else
{
m = max(F[i][j],m);
if(F[i][j] == m)
{
posB = i;
posV = j;
}
}
}
}
Param[0] = grid[posB];
Param[1] = gridV[posV];
delete[] F;
delete[] grid;
return Param;
}
#endif __MA1_H_INCLUDED__
#ifndef __KALMANFILTERING_H_INCLUDED__
#define __KALMANFILTERING_H_INCLUDED__
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "MyLib.h"
#include <array>
using namespace std;
double* KalmanFiltering(std::string path, const double sigmaeps, const double sigmaeta, double ret[], string data[], int size)
{
//srand (time(NULL));
string *Realdata;
double *Sim;
std::ifstream filein;
filein.open (path);
int count = 0;
double *a;
double *P;
if(filein.fail())
{
std::cout << "File opening error" << std::endl;
return 0;
}
else
{
string line;
while(getline(filein,line))
{
count++;
}
filein.close();
Sim = new double[count];
Realdata = new string[count];
filein.open(path);
for(int i = 0; i<count; i++)
{
getline(filein,line);
Realdata[i] = line;
//cout << Realdata[i];
}
}
filein.close();
a = new double[count];
P = new double[count];
a[0]= mean(ret, size);
P[0]= variance(ret, size);
int *idx;
idx = new int[size];
for(int i=0; i < count;i++)
{
const char *chrR = Realdata[i].c_str();
double GhostR= 0.0;
for(int j=0; j < size; j++)
{
const char *chrD = data[j].c_str();
if(strcmp(chrR, chrD)== 0)
{
idx[j] = 1.0;
GhostR += ret[j];
}
else
idx[j] = 0.0;
}
if(cumsumC(idx,size) != 0)
{
double v = GhostR/cumsumC(idx,size) - a[i];
double F = P[i] + sigmaeps*sigmaeps;
a[i+1] = a[i]+(P[i]/F)*v;
P[i+1] = P[i]*(1- P[i]/F) + sigmaeta*sigmaeta;
}
else
{
a[i+1]= a[i];
P[i+1]= P[i] + sigmaeta*sigmaeta;
}
}// Loop over real data
for(int i=0; i < count;i++)
{
double GhostR = 0;
int counter = 0;
const char *chrR = Realdata[i].c_str();
for(int j=0; j < size; j++)
{
if(strcmp(chrR,data[j].c_str())== 0)
{
idx[j] = 1.0;
counter++;
GhostR += ret[j];
}
else
idx[j] = 0;
}
if(cumsumC(idx,size) != 0)
{
Sim[i] = GhostR/counter;
}
else
{
double s = rand() % 9999 + 1;
Sim[i] = a[i] + pow(P[i],2)*NormalCDFInv(s/10000);
}
}// Loop over Simulation
delete[] idx;
//delete[] a;
//delete[] P;
delete[] Realdata;
return Sim;
}// Kalman End
#endif _KALMANFILTERING_H_INCLUDED_
You do not need to use arrays for this. C++ has a nice std::vector class which requires no deletion, or manual memory management, do use it:
http://www.cplusplus.com/reference/vector/vector/
double *price;
string *data;
data = new string[c];
price = new double[c];
can be written as:
std::vector<double> price;
std::vector<std::string> data;
data.reserve(c);
price.reserve(c);
and you do not worry about allocation/deallocation of funny memory blocks.