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.
Related
I keep getting this error and have no idea how to fix it because I don't see anything wrong with my code.
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#define GREEN "\033[32m"
#define RED "\033[31m"
#define RESET "\033[0m"
void file_create(std::string name) {
std::ifstream file(name);
if (file.is_open()) {
file.close();
std::cout << "File already exists..." << std::endl;
main();
}
else {
file.close(); std::ofstream newFile(name);
if (newFile.is_open())
std::cout << GREEN "New file successfully created..." << RESET << std::endl;
else
std::cout << RED "File could not be created" << RESET << std::endl;
newFile.close();
}
}
int main() {
}
The main function is not intended to be invoked from your code. It is also a nonsense since it is called automatically when program starts. But if you need some alternative main to be invoked upon some condition, you can call it inside your main function
...
int alternative_main()
{
place your program there
}
...
void file_create(std::string name) {
...
if (file.is_open()) {
...
alternative_main()
}
else {
...
}
}
Suppose your main looks like this
int main() {
file_create("myfile");
}
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#define GREEN "\033[32m"
#define RED "\033[31m"
#define RESET "\033[0m"
int main(); // defined before file_create
void file_create(std::string name) {
std::ifstream file(name);
if (file.is_open()) {
file.close();
std::cout << "File already exists..." << std::endl;
main();
}
else {
file.close(); std::ofstream newFile(name);
if (newFile.is_open())
std::cout << GREEN "New file successfully created..." << RESET << std::endl;
else
std::cout << RED "File could not be created" << RESET << std::endl;
newFile.close();
}
}
int main() {
}
Define int main() above file_create() so you can call it in file_create
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
//use this instead of repetitively using std all the time
#define GREEN "\033[32m"
#define RED "\033[31m"
#define RESET "\033[0m"
void file_create(string name) {
ifstream file(name);
if (file.is_open()) {
file.close();
cout << "File already exists..." << endl;
return 0;
}
else {
file.close();
ofstream newFile(name);
if (newFile.is_open())
cout << GREEN "New file successfully created..." << RESET << endl;
else
cout << RED "File could not be created" << RESET << endl;
newFile.close();
}
}
int main() {
string name;
cin>>name;
file_create(name);
}
try using this way...
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;
}
From the console i am asking for a hexadecimal string to convert to a pointer to reference an item in memory.
#include <iostream>
#include <sstream>
#include <Windows.h>
int char_to_pointer(std::string input);
int main() {
int sample = 100; // lets say this address is 0xc1f1
std::string input_;
std::cout << "addr:" << &sample << std::endl;
std::cout << "what is the memory address?:" << std::endl;
std::cin >> input_;
unsigned int inp = char_to_pointer(input_);
std::cout << "imp: " << inp << std::endl;
Sleep(10000);
return 0;
}
int char_to_pointer(std::string input) {
return std::stoul(input, nullptr, 16);
}
My problem is that char_to_pointer only converts the hex string into a decimal.
this is what i want:
input: "0xc1f1"
output: 100
I found the solution:
#include <iostream>
#include <sstream>
#include <Windows.h>
#include <string>
int *char_to_pointer(std::string input);
int main() {
int sample = 100; // lets say this address is 0xc1f1
std::string input_;
std::cout << "addr:" << &sample << std::endl;
std::cout << "what is the memory address?:" << std::endl;
std::cin >> input_;
int *inp = char_to_pointer(input_);
std::cout << "imp: " << inp << std::endl;
std::cout << "imp*: " << *inp << std::endl;//This was my solution
std::cout << "imp&: " << &inp << std::endl;
Sleep(10000);
return 0;
}
int *char_to_pointer(std::string input) {
return (int *)std::stoul(input, nullptr, 16);
}
the program should read from 2 files (author.dat and citation.dat) and save them into a map and set;
first it reads the citationlist without problem, then it seems to properly read the authors and after it went through the whole list (author.dat) a floating point exception arises .. can't quite figure out why
seems to happen in author.cpp inside the constructor for authorlist
author.cpp:
#include <fstream>
#include <iostream>
#include "authors.h"
using namespace std;
AuthorList::AuthorList(char *fileName) {
ifstream s (fileName);
int idTemp;
int nrTemp;
string nameTemp;
try {
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
} catch (EOFException){}
}
author.h:
#ifndef CPP_AUTHORS_H
#define CPP_AUTHORS_H
#include <iostream>
#include <map>
#include <string>
#include "citations.h"
class Author {
public:
Author (int id, int nr, std::string name) :
articleID(id),
authorNR(nr),
authorName(name){}
int getArticleID() const {
return articleID;
}
std::string getAuthorName() const {
return authorName;
}
private:
int articleID;
int authorNR;
std::string authorName;
};
class AuthorList {
public:
AuthorList(char *fileName);
std::pair<std::multimap<int,Author>::const_iterator, std::multimap<int,Author>::const_iterator> findAuthors(int articleID) {
return authors.equal_range(articleID);
}
private:
std::multimap<int,Author> authors;
};
#endif //CPP_AUTHORS_H
programm.cpp:
#include <iostream>
#include <cstdlib>
#include "citations.h"
#include "authors.h"
#include "authorCitation.h"
using namespace std;
int main(int argc, char *argv[]){
CitationList *cl;
AuthorList *al;
//check if argv array has its supposed length
if (argc != 4){
cerr << "usage: programm article.dat citation.dat author.dat";
return EXIT_FAILURE;
}
//inserting citation.dat and author.dat in corresponding lists (article.dat not used)
cl = new CitationList(argv[2]);
al = new AuthorList(argv[3]);
try {
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
acl->printAuthorCitationList2File("authorcitation.dat");
} catch (EOFException){
cerr << "something went wrong while writing to file";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
All files:
https://drive.google.com/file/d/0B734gx5Q_mVAV0xWRG1KX0JuYW8/view?usp=sharing
I am willing to bet that the problem is caused by the following lines of code:
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
You are calling a member function using an uninitialized pointer. I suggest changing the first line to:
AuthorCitationList *acl = new AuthorCitationList;
Add any necessary arguments to the constructor.
While you are at it, change the loop for reading the data also. You have:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
When you do that, you end up adding data once after the end of line has been reached. Also, you seem to have the last line in the wrong place. It seems to me that it should be outside the while loop.
You can use:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
// Break out of the loop when reading the
// data is not successful.
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
You can simplify it further by using:
while (s >> idTemp >> nrTemp >> nameTemp){
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
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.