Hi I have a problem with my program, it opens a file correctly in the lineCounter
function, counts and throws the number of lines in the file to the console, but then in the readFile
function it grinds something and then throws the error below. It seems to me that the problem lies in dynamic memory allocation, because when I did the same thing in the main function with local variables everything worked fine.
Console output:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lineCounter(string);
void readFile(string);
string encryption(string);
string decryption(string);
int howMuch;
int linesOfFile;
string buffer;
string pathToFile;
string *fileContent = new string[linesOfFile];
int main()
{
cout << "If your file is in the program folder enter the name itself with the extension. If it is not, give the full path." << endl;
cin >> pathToFile;
cin.ignore();
lineCounter(pathToFile);
cout << linesOfFile;
readFile(pathToFile);
cout << *fileContent << endl;
delete [] fileContent;
fileContent = NULL;
return 0;
}
void lineCounter(string pathToFile)
{
fstream file;
file.open(pathToFile, ios::in | ios::binary);
if (file.is_open())
{
do
{
file >> buffer;
linesOfFile++;
}while(!file.eof());
file.seekg(0);
file.close();
return;
}
else
cout << "A critical error occurred" << endl;
return;
}
void readFile(string pathToFile)
{
fstream file;
file.open(pathToFile, ios::in);
if (file.is_open())
{
/*int i =0;
do
{
file >> fileContent[i]; // tutaj jakis bląd
i++;
}while(!file.eof());*/
for(int i = 0; i < linesOfFile; i++)
{
file >> buffer;
fileContent[i] = buffer;
}
file.seekg(0);
file.close();
return;
}
else
cout << "A critical error occurred" << endl;
return;
}
string encryption(string word)
{
int asciiProtection;
for(int i = 0; i < word.length(); i++)
{
asciiProtection = word[i] + howMuch;
if(asciiProtection < 65)
word[i] += (26 + howMuch);
else if(asciiProtection > 90)
word[i] -= (26 - howMuch);
else
word[i] += howMuch;
}
return word;
}
string decryption(string word)
{
int asciiProtection;
for(int i = 0; i < word.length(); i++)
{
asciiProtection = word[i] - howMuch;
if(asciiProtection < 65)
word[i] += (26 - howMuch);
else if(asciiProtection > 90)
word[i] -= (26 + howMuch);
else
word[i] -= howMuch;
}
return word;
}