Why does the output file come up empty - c++

I'm working on a program that is supposed to make use of async and futures but i have come across a problem. When an output file is created nothing is in the file. It is just a blank file. I'm not sure if the issue s with reading the original file or write onto a new one I'm also usure if I have properly utilized async so any corrections would be a appreciated.
#include <fstream>
#include <string>
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <future>
#include <vector>
#include <stdexcept>
#include <utility>
#include <sstream>
#include <stdlib.h>
#include <cstdlib>
#include <ctime>
using namespace std;
int prnumber;
static bool bCheckFinished = false;
string guess;
bool process(std::string sFileIn, std::string sFileOut) {
ifstream in(sFileIn);
vector<vector<string>> vsFields;
ofstream outPutFile;
outPutFile.open(sFileOut, std::ofstream::out | std::ofstream::trunc);
if (in) {
string sLine;
while (getline(in, sLine)) {
stringstream sep(sLine);
string sField;
vsFields.push_back(vector<string>());
while (getline(sep, sField, ',')) {
vsFields.front().push_back(sField);
}
}
}
if (outPutFile.is_open()) {
for (auto row : vsFields) {
for (auto field : row) {
outPutFile << field << "," << std::endl;
}
}
}
std::cout << "\n File Successfully Read!" << std::endl;
return true;
}
bool prime(int prnumber) {
std::cout << "Please enter a number" << std::endl;
std::cin >> prnumber;
std::cout << "Processing" << std::endl;
for (int i = 2; i < prnumber; ++i) if (prnumber%i == 0) return false;
return true;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
std::future<bool> fileProcA = std::async(process, "unigram_freq.cvs", "Word_list.txt");
std::future<bool> fut = std::async(prime, prnumber);
bool pr = fut.get();
bool fileProc = false;
while (!fileProc) {
fileProc = fileProcA.get();
}
auto end = std::chrono::high_resolution_clock::now();
if (pr) std::cout << "The number is prime!" << endl;
else std::cout << "It is not prime";
double elapsed = (std::chrono::duration<double, std::milli>(end - start).count());
std::cout << "The time elapsed is " << elapsed << "ms" << std::endl;
return 0;
}

Related

Creating new txt files with c++ program, naming with variables

I have created a program and I want to create with it files like aff1.txt, aff2.txt, etc. In these files, I want to have here a text created this way: It will open the file: text.txt and it will take each sentence, copy it 4700/sentence length times to each file. But it isn't working, when: cout << ss << endl;, it writes to cmd nothing, while there should be something, which was assigned before. What should I do?
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <string.h>
#include <sstream>
using namespace std;
int main()
{
ifstream vstup("text.txt"); // 4700,2700,2200,1700
string vety;
getline(vstup,vety);
vstup.close();
string ss="affn.txt";
char q[vety.length()];
for (int u=0;u<vety.length();u++)
{
q[u] = vety[u];
}
int l=0,m=0,n=0;
int v,i,e,o;
char vl[999999];
//cout << vety.length() << endl;
for (i=0;i<vety.length();i++)
{
//cout << "ss" << endl;
if (q[i]=='.')
{
// cout << "ss" << endl;
v=4700/i;
for (e=0;e<v;e++)
{
//cout << "ss" << endl;
for (o=0;o<i-l;o++)
{
// cout << "ss" << endl;
m=o+e*(i-l);
vl[m]=q[o+l];
}
}
l=l+i;
cout << vl << endl;
n++;
//ofstream aff("aff.txt");
//aff << vl << endl;
//aff.close();
ss[3]=n;
ofstream writer(ss.c_str());
//writer.open(ss.c_str());
writer << vl << endl;
writer.close();
cout << ss << endl;
ss.clear();
}
}
return 0;
}

looping in background while running other statements c++

I want to make a program which displays current time that ticks in background then is it possible to initialize cin input processes while it is ticking?
just for fun:
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include <mutex>
#include <ctime>
std::mutex more_lock;
std::string more_output;
void set_more_output(const std::string& more)
{
std::lock_guard<std::mutex> lock(more_lock);
more_output = more;
}
std::string get_more_output()
{
std::lock_guard<std::mutex> lock(more_lock);
return more_output;
}
std::atomic_bool running {true};
std::thread start_timer_runner()
{
return std::thread([&]{
while(running) {
using namespace std::chrono;
using namespace std::chrono_literals;
auto now = system_clock::to_time_t(system_clock::now());
auto now_str = std::string(std::ctime(&now));
now_str.pop_back(); // ctime adds new line
std::cout << "\r" << now_str << " | " << get_more_output() << std::flush;
std::this_thread::sleep_for(1s);
}
});
}
void parse_decimals()
{
int x;
set_more_output("please enter a decimal: ");
while(std::cin >> x)
{
set_more_output("thanks! you entered " + std::to_string(x) + ", please enter a new decimal: ");
}
}
int main()
{
auto timer = start_timer_runner();
parse_decimals();
running = false;
timer.join();
std::cout << std::endl << "bye bye!" << std::endl;
}

Visual Studio 2015 C2011 'Class' type redefinition

im currently working on a small console app, i read from some files, and i have made a simple animated loading bar thread to show the progress of file reading (sometimes the file are really huge)
i have read on the microsoft documentation and on the forum and that error seems to suggest that i defined the class multiple time.
but i did include all the header blocks to prevent this from happenning, any of you see my mistake, probly obvious, i havent done c++ in years.
here is the code
fileReader.h
#pragma once
#ifndef FILEREADER_H // must be unique name in the project
#define FILEREADER_H
#include <vector>
using namespace std;
class fileReader {
private:
public:
vector<string> readTextFile(string path);
unsigned int getSize();
unsigned int getLoadedBytes();
};
#endif // FILEREADER_H
#pragma once
fileReader.cpp
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <thread>
#include "numbers.h"
#include "loadingBar.h"
using namespace std;
class fileReader {
private:
public :
vector<string> list;
int i;
unsigned int size;
unsigned int loadedBytes;
string line;
std::thread* barThread;
vector<string> fileReader::readTextFile(string path) {
ifstream file(path.c_str(), ios::in | ios::binary | ios::ate);
i = 0;
size = 0;
loadedBytes = 0;
ifstream file(path.c_str(), ios::in | ios::binary | ios::ate);
if (file.is_open()) {
size = file.tellg();
cout << "\t" << path << " (" << formatNumbers(size) << " bytes)" << endl;
file.clear();
file.seekg(0, ios::beg);
barThread = new std::thread(&loadingBar::run, *this);
while (file >> line) {
list.push_back(line);
loadedBytes += strlen(line.c_str());
i++;
}
}
else {
cout << "Error reading : \"" << path << "\"" << endl;
exit(EXIT_FAILURE);
}
file.close();
return list;
}
unsigned int fileReader::getSize() { return size; }
unsigned int fileReader::getLoadedBytes() { return loadedBytes; }
};
loadingBar.h
#pragma once
#ifndef LOADINGBAR_H
#define LOADINGBAR_H
#include<stdlib.h>
#include<string>
#include<iomanip>
#include "numbers.h"
#include "fileReader.h"
using namespace std;
class loadingBar {
public:
void notififyFinish();
void notifyError();
void notifiError(string);
void drawloadingBar();
void drawPathBar();
void drawBytesBar();
void setLoadedUnits(int);
void setTotalUnits(int);
void run(fileReader*);
};
#endif // NUMBERS_H
loadingBar.cpp
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include "numbers.h"
#include "fileReader.h"
using namespace std;
class loadingBar {
private:
public:
double totalUnits = 1;
double loadedUnits = 0;
char loadedChar = '/';
char emptyChar = ' ';
int barLength = 50;
double percent;
int nbChar;
void notiftyFinish() {
cout << " Ok" << endl;
//exit(EXIT_SUCCESS);
}
void notifiyError() {
cout << " Error !" << endl;
//exit(EXIT_FAILURE);
}
void notifiyError(string errMess) {
cout << " Error !" << endl << "\t" << errMess;
//exit(EXIT_FAILURE);
}
void drawLoadingBar() {
cout << fixed;
cout << "\rLoading [";
for (int i = 0; i < nbChar; i++)
cout << loadedChar;
for (int i = nbChar; i < barLength - 1; i++)
cout << emptyChar;
cout << "] " << setprecision(0) << percent << "%";
}
void drawPathBar(string path) {
cout << fixed;
cout << "\rLoading [ ";
cout << path;
cout << " ] " << setprecision(0) << percent << "%";
}
void drawBytesBar() {
cout << fixed;
cout << "\rLoading [ ";
cout << formatNumbers(loadedUnits) << " / " << formatNumbers(totalUnits);
cout << " ] " << setprecision(0) << percent << "%";
}
void setLoadedUnits(int newValue) {
if (newValue > 0)
loadedUnits = newValue;
}
void setTotalUnits(int value) {
if (value > 0)
totalUnits = value;
}
void run(fileReader *f) {
setTotalUnits(f->getSize());
setLoadedUnits(f->getLoadedBytes());
while (loadedUnits <= totalUnits) {
setLoadedUnits(f->getLoadedBytes());
percent = ((double)(loadedUnits / totalUnits) * 100);
nbChar = (int)(percent / (int)(100 / barLength));
drawLoadingBar();
//setLoadedUnits((int)loadedUnits + 10);
if (loadedUnits >= totalUnits) notiftyFinish();
}
}
};
Your .cpp files redefine your classes. You've already defined them in the respective .h files. All you need to include in your .cpp files is the implementations. They should look more like this:
fileReader.cpp
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <thread>
#include "numbers.h"
#include "loadingBar.h"
vector<string> fileReader::readTextFile(string path) {
ifstream file(path.c_str(), ios::in | ios::binary | ios::ate);
i = 0;
size = 0;
loadedBytes = 0;
ifstream file(path.c_str(), ios::in | ios::binary | ios::ate);
if (file.is_open()) {
size = file.tellg();
cout << "\t" << path << " (" << formatNumbers(size) << " bytes)" << endl;
file.clear();
file.seekg(0, ios::beg);
barThread = new std::thread(&loadingBar::run, *this);
while (file >> line) {
list.push_back(line);
loadedBytes += strlen(line.c_str());
i++;
}
}
else {
cout << "Error reading : \"" << path << "\"" << endl;
exit(EXIT_FAILURE);
}
file.close();
return list;
}
unsigned int fileReader::getSize() { return size; }
unsigned int fileReader::getLoadedBytes() { return loadedBytes; }
Similarly for loadingBar.cpp.

ifstream::read not working?

I am trying to read from a .csv file. There are two functions below, one for writing and one for reading.
The file contains a simple table:
date,first,second
1 a one
2 b two
3 c three
4 c four
For some reason, the statement while(file_stream.read(&c,1)); does not read anything. It stops at the first character and I'm dumbfounded as to why. Any clues?
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
std::string filename;
std::string line_string;
ifstream file_stream;
stringstream ss;
vector< vector<string> > vec;
char c;
void read_file()
{
filename = "test.csv";
cout << filename << endl;
file_stream.open(filename.c_str(),ios::out|ios::binary);
if(file_stream.fail())
{
cout << "File didn't open" << endl;
return;
}
if(file_stream.is_open())
cout << "file opened" << endl;
while(file_stream.read(&c,1)); // this isn't working
{
cout <<"char c is: " << c;
ss << noskipws << c;
}
file_stream.close();
cout << "string is: " << ss.str() << endl;
//get each line
int counter = 0;
vector<string> invec;
while(getline(ss,line_string,'\n'))
{
string header_string;
stringstream header_stream;
header_stream << line_string;
while(getline(header_stream, header_string,','))
{
invec.push_back(header_string);
}
invec.push_back(header_string);
vec.push_back(invec);
invec.clear();
counter++;
}
}
void test_output()
{
for(int i = 0; i < vec.size();i++)
{
for(int in = 0; in < vec[0].size(); in++)
cout << vec[i][in] << " ";
cout << endl;
}
}
int main()
{
read_file();
test_output();
}
Look very very carefully at the line that is not working:
while(file_stream.read(&c,1)); // this isn't working
{
cout <<"char c is: " << c;
ss << noskipws << c;
}
The ; character at the end of the while statement does NOT belong! You are running a no-body loop that does not terminate until read() fails, and THEN your code enters the bracketed block to output the last character that was successfully read (if any).
You need to remove that erroneous ; character:
while(file_stream.read(&c,1)) // this works
{
cout <<"char c is: " << c;
ss << noskipws << c;
}
Now, the real question is - why are you reading the input file character-by-character into a std::stringstream in the first place? You can use std::getline() with the input std::ifstream directly:
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
std::vector< std::vector<std::string> > vec;
void read_file()
{
std::string filename = "test.csv";
std::cout << filename << std::endl;
std::ifstream file_stream;
file_stream.open(filename.c_str(), ios::binary);
if (!file_stream)
{
std::cout << "File didn't open" << std::endl;
return;
}
std::cout << "file opened" << std::endl;
//get each line
std::vector<std::string> invec;
std::string line;
int counter = 0;
if (std::getline(file_stream, line))
{
std::istringstream iss(line);
while (std::getline(iss, line, ','))
invec.push_back(line);
vec.push_back(invec);
invec.clear();
++counter;
while (std::getline(file_stream, line))
{
iss.str(line);
while (iss >> line)
invec.push_back(line);
vec.push_back(invec);
invec.clear();
++counter;
}
}
}
void test_output()
{
if (!vec.empty())
{
for(int in = 0; in < vec[0].size(); ++in)
std::cout << vec[0][in] << ",";
std::cout << std::endl;
for(int i = 1; i < vec.size(); ++i)
{
for(int in = 0; in < vec[i].size(); ++in)
std::cout << vec[i][in] << " ";
std::cout << std::endl;
}
}
}
int main()
{
read_file();
test_output();
}

C++ with Boost Library. Reading Columns. Excel/CSV

I'm reading in a CSV that has 3 columns. On each column I need to perform the mean, var, and std calculations. I'm able to get the output for the first column but dont know how to have it print all 3 columns. Thanks.
I tried adding ','
after line
in
while (getline(inNew, line, ','))
but that doesnt work for me
int main()
{
ifstream inNew("C:/Users/A.csv");
accumulator_set<double, stats<tag::mean, tag::variance >> acc;
if (inNew)
{
string line;
while (getline(inNew, line))
{
acc(stod(line));
}
cout << "Expected return is: " << mean(acc) << std::endl;
cout << "Variance: " << variance(acc) << std::endl;
cout << "Std Dev: " << sqrt(variance(acc)) << std::endl;
}
inNew.close();
system("pause");
return 0;
}
Since you're already using boost, use boost::split to split each line into its columns. Then accumulate each column separately. You'll need an accumulator_set for each column.
Code might look something like this:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/algorithm/string.hpp>
int main()
{
using namespace std;
using namespace boost;
using namespace boost::accumulators;
ifstream inNew("C:/Users/A.csv");
size_t columns = 3;
vector<accumulator_set<double, stats<tag::mean, tag::variance>>> acc(columns);
if (inNew)
{
string line;
while (getline(inNew, line))
{
vector<string> strs;
split(strs, line, is_any_of("\t ,"));
if (strs.size() == columns)
{
for (size_t i = 0; i < columns; ++i)
{
acc[i](stod(strs[i]));
}
}
}
for (size_t i = 0; i < columns; ++i)
{
cout << "Stats for column " << (i + 1) << endl;
cout << "Expected return is: " << mean(acc[i]) << endl;
cout << "Variance: " << variance(acc[i]) << endl;
cout << "Std Dev: " << sqrt(variance(acc[i])) << endl;
}
}
inNew.close();
system("pause");
return 0;
}
Of course, you could make this more fancy and robust by not hardcoding the number of columns.