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

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;
}

Related

Moving the input file with c++

I want to be able to enter any file in MoveFile() and it will move the file to this folder: C:\folder\fl.txt. When I enter MoveFileA("C:\\fl.txt", "C:\\folder\\fl.txt"); Then everything works, but I need to move the first file (the one that is fl.txt) to folder ...
How can this be implemented so as not to always enter the file name (C:\folder\fl.txt) so that it auto inputs it?
Here is my code:
#include <iostream>
#include <string>
#include <Windows.h>
#include <stdio.h>
#include <cstdlib>
using namespace std;
int main() {
MoveFileA("C:\\fl.txt", "C:\\folder\\fl.txt");
cout << "Operation Succesful" << endl;
cout << endl;
system("pause");
}
I need something like:
int main() {
int path_a;
cin >> path_a;
MoveFileA("path_a", "C:\\folder\\path_a");
cout << "Operation Succesful" << endl;
cout << endl;
system("pause");
}
Perhaps you are looking for something like this:
#include <iostream>
#include <string>
#include <cstdlib>
#include <Windows.h>
using namespace std;
int main() {
string filename;
cin >> filename;
if (MoveFileA(("C:\\"+filename).c_str(), ("C:\\folder\\"+filename).c_str()))
cout << "Operation Successful" << endl;
else
cout << "Operation Failed" << endl;
cout << endl;
system("pause");
}
Though, if you are using C++17 or later, you might consider a pure C++ solution using std::filesystem::rename() instead of the Windows-specific MoveFileA() function, eg:
#include <iostream>
#include <string>
#include <filesystem>
#include <system_error>
#include <cstdlib>
using namespace std;
namespace fs = std::filesystem;
int main() {
fs::path filename;
cin >> filename;
fs::path root("C:\\");
error_code ec;
fs::rename(root / filename, root / "folder" / filename, ec);
if (ec)
cout << "Operation Failed" << endl;
else
cout << "Operation Successful" << endl;
cout << endl;
system("pause");
}

Why does my vector::erase call throw "vector subscript out of range"?

I'm writing a program that saves words from a .txt file in vector words, calculates how many words are there (num_elements) and prints these words randomly to the screen (no duplicates).
It all works fine up until rw.erase line, which just spits out the error "vector subscript out of range".
Why is my erase call throwing "vector subscript out of range"?
#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
#include <direct.h>
#include <filesystem>
#include <time.h>
#include <random>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
void path_to_main_dir() {
string path = "C:/Randomizer/";
for (const auto& entry : experimental::filesystem::directory_iterator(path)) {
cout << entry.path() << endl;
}
}
int main() {
path_to_main_dir();
string dateread;
printf("Which file do you want to open? ");
cout << "---------------------------------------------------------------------------------------------------------" << endl;
path_to_main_dir();
cout << endl;
cout << "---------------------------------------------------------------------------------------------------------" << endl;
cout << "User: ";
getline(cin, dateread);
string path_to_file = "C:/Randomizer/" + dateread + ".txt";
ifstream readfile(path_to_file.c_str());
vector<string> words;
string word;
while (getline(readfile, word))
{
words.push_back(word);
}
readfile.close();
srand(time(NULL));
string randomword;
vector<string> rw = { words };
int num_elements = size(words);
cout << endl;
cout << "Number of words in the file: ";
cout << num_elements;
cout << endl;
for (unsigned int a = 0; a < num_elements; a = a + 1)
{
randomword = rw[rand() % num_elements];
cout << randomword << endl;
rw.erase(remove(rw.begin(), rw.end(), randomword), rw.end());
num_elements -= 1;
system("pause");
}
goto firstline;
return 0;
}
If the error only happens in the case where there are duplicates, it could be because the num_elements is wrong. The remove/erase call will have deleted as many duplicates as there are, but num_elements has only been reduced by one.
Fortunatly, vectors know their own size, so rather than trying to remember its internal information for it, you can just ask!
int main()
{
//...
//Code to read words from file
//...
cout << "Number of words in file: " << words.size() << endl;
while(!words.empty())
{
string randomWord = words[rand() % words.size()];
cout << randomWord << endl;
words.erase(remove(words.begin(), words.end(), randomWord), words.end());
}
return 0;
}
From what I can see, you only use words to create rw, so we could just use words directly instead.

C++ function unable to another function and ends automaticly

So I was making a file editor using c++ and it has 3 functions and it needs to call each other to work properly.But When code tries to call other functions it end abnormly .
I tried changing the order of functions but it does nothing.It will compile properly without warnings
it needs output the contents of the file.
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#include <string>
#include <iomanip>
#include <unistd.h>
#include <sstream>
using namespace std;/* std */
/* data */
char buffer;
std::string fname;
int reader(){
std::ifstream readfile;
readfile.open(fname.c_str());
readfile>>buffer;
std::cout << buffer<< '\n';
int write();
}
int options(){
cout << "************************"<< '\n';
cout << "* Starting File editor *"<< '\n';
cout << "************************"<< '\n';
cout << "* Enter Filename *"<< '\n';
cin >>fname;
cout << "Opening File"<<fname<< '\n';
int reader();
std::cout << buffer<< '\n';
}
int write(){
cout << "writing to file " << '\n';
std::ofstream writefile;
writefile.open(fname.c_str());
writefile<<buffer;
cout << "writing done " << '\n';
}
int main()
{
/* code */
options();
return 0;
}
options() is not calling reader(), and reader() is not calling write(). In both cases, you are simply declaring functions, not actually calling them.
int reader(){
...
int write(); // <-- a declaration, not a call!
}
int options(){
...
int reader(); // <-- a declaration, not a call!
...
}
int main() {
...
options(); // <-- a call, not a declaration!
..
}
Try this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* data */
char buffer;
std::string fname;
int reader(){
cout << "opening file " << fname << '\n';
std::ifstream readfile(fname.c_str());
readfile >> buffer;
std::cout << buffer << '\n';
}
int write(){
cout << "writing to file " << '\n';
std::ofstream writefile(fname.c_str());
writefile << buffer;
cout << "writing done" << '\n';
}
int options(){
cout << "************************"<< '\n';
cout << "* Starting File editor *"<< '\n';
cout << "************************"<< '\n';
cout << "* Enter Filename *"<< '\n';
cin >> fname;
reader();
write();
}
int main() {
/* code */
options();
return 0;
}
In addition to the comments above about calling the functions, it seems like it would be good to initialize buffer as a char array as shown below:
#include <iostream>
#include <fstream>
//#include <bits/stdc++.h>
#include <string>
#include <iomanip>
#include <unistd.h>
#include <sstream>
using namespace std;/* std */
/* data */
char buffer[]{"Short test"};
std::string fname;
void write(){
cout << "writing to file " << '\n';
std::ofstream writefile;
writefile.open(fname.c_str());
writefile<<buffer;
cout << "writing done " << '\n';
}
void reader(){
std::ifstream readfile;
readfile.open(fname.c_str());
readfile>>buffer;
std::cout << buffer<< '\n';
write();
}
void options(){
cout << "************************"<< '\n';
cout << "* Starting File editor *"<< '\n';
cout << "************************"<< '\n';
cout << "* Enter Filename *"<< '\n';
cin >>fname;
cout << "Opening File"<<fname<< '\n';
reader();
std::cout << buffer<< '\n';
}
int main()
{
/* code */
options();
return 0;
}
You can declare functions(not compulsory in your case) after all #include statements like:
int reader();
int write();
int options();
You call write function as write(); reader function as reader();
Since functions are not returning anything you could change int reader() to void reader(), int write() to void write() and so on. Keep main as int main() though.

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.

Function not recognized within scope

I've almost finished writing a program that will detect palindromes from a file and output a new file highlighting the palindromes but I'm stuck on a really dumb error. I'm trying to write a test for one of my methods (TDD) and, for some reason, it's not recognizing the function as within the scope.
I'm calling the isPalindrome(string s) method (declared in PalindromeDetector.h) in my isPalindromeTest() method (declared in PalindromeDetectorTest.h) but, for some reason, it's not recognizing it as within the scoope.
I feel like everything should be working but it just isn't. Any help you can provide would be greatly appreciated. Below is my code:
PalindromeDetector.h
#ifndef PALINDROMEDETECTOR_H_
#define PALINDROMEDETECTOR_H_
#include <iostream>
using namespace std;
class PalindromeDetector {
public:
void detectPalindromes();
bool isPalindrome(string s);
};
#endif /* PALINDROMEDETECTOR_H_ */
PalindromeDetector.cpp
#include "PalindromeDetector.h"
#include "Stack.h"
#include "ArrayQueue.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetector::detectPalindromes() {
cout << "Enter the name of the file whose palindromes you would like to detect:" << flush;
string fileName;
cin >> fileName;
cout << "Enter the name of the file you would like to write the results to: " << flush;
string outFileName;
cin >> outFileName;
fstream in;
in.open(fileName.c_str());
assert(in.is_open());
ofstream out;
out.open(outFileName.c_str());
assert(out.is_open());
string line;
while(in.good()){
getline(in, line);
line = line.erase(line.length()-1);
if(line.find_first_not_of(" \t\v\r\n")){
string blankLine = line + "\n";
out << blankLine;
} else if(isPalindrome(line)){
string palindromeYes = line + " ***\n";
out << palindromeYes;
} else {
string palindromeNo = line + "\n";
out << palindromeNo;
}
if(in.eof()){
break;
}
}
in.close();
out.close();
}
bool PalindromeDetector::isPalindrome(string s){
unsigned i = 0;
Stack<char> s1(1);
ArrayQueue<char> q1(1);
while(s[i]){
char c = tolower(s[i]);
if(isalnum(c)){
try{
s1.push(c);
q1.append(c);
} catch(StackException& se) {
unsigned capS = s1.getCapacity();
unsigned capQ = q1.getCapacity();
s1.setCapacity(2*capS);
q1.setCapacity(2*capQ);
s1.push(c);
q1.append(c);
}
}
i++;
}
while(s1.getSize() != 0){
char ch1 = s1.pop();
char ch2 = q1.remove();
if(ch1 != ch2){
return false;
}
}
return true;
}
PalindromeDetectorTest.h
#ifndef PALINDROMEDETECTORTEST_H_
#define PALINDROMEDETECTORTEST_H_
#include "PalindromeDetector.h"
class PalindromeDetectorTest {
public:
void runTests();
void detectPalindromesTest();
void isPalindromeTest();
};
#endif /* PALINDROMEDETECTORTEST_H_ */
PalindromeDetectorTest.cpp
#include "PalindromeDetectorTest.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetectorTest::runTests(){
cout << "Testing palindrome methods... " << endl;
detectPalindromesTest();
isPalindromeTest();
cout << "All tests passed!\n" << endl;
}
void PalindromeDetectorTest::detectPalindromesTest(){
cout << "- testing detectPalindromes()... " << flush;
fstream in;
string fileName = "testFile.txt";
in.open(fileName.c_str());
assert(in.is_open());
cout << " 1 " << flush;
ofstream out;
string fileOutName = "testFileOut.txt";
out.open(fileOutName.c_str());
assert(out.is_open());
cout << " 2 " << flush;
cout << " Passed!" << endl;
}
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
// test with one word palindrome
string s1 = "racecar";
assert(isPalindrome(s1) == true); // these are not recognized within the scope
cout << " 1 " << flush;
// test with one word non-palindrome
string s2 = "hello";
assert(isPalindrome(s2) == false); // these are not recognized within the scope
cout << " 2 " << flush;
// test with sentence palindrome
string s3 = "O gnats, tango!";
assert(isPalindrome(s3) == true); // these are not recognized within the scope
cout << " 3 " << flush;
// test with sentence non-palindrome
string s4 = "This is not a palindrome.";
assert(isPalindrome(s4) == false); // these are not recognized within the scope
cout << " 4 " << flush;
cout << " Passed!" << endl;
}
isPalindrome is a member function of PalindromeDetector, but you are trying to call it from within a PalindromeDetectorTest method. If the test class derived from PalindromeDetector this would work, but there isn't (and almost certainly shouldn't be) any such relationship between them.
You need a PalindromeDetector object to call the method on. Probably just as simple as this:
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
PalindromeDetector sut; // "subject under test"
// test with one word palindrome
string s1 = "racecar";
assert(sut.isPalindrome(s1) == true);
// etc.
}
You could also make the PalindromeDetector methods static since the object doesn't appear to have any state. Then you could simply call PalindromeDetector::isPalindrome(s1); without the need to create an instance.