Where I am stuck at is the EncryptString function. The EncryptFile function will take a .txt file and convert the .txt to a C string equivalent, then pass that into the EncrpytString function. When I pass it in, the Substitution function will do its work with the cipher string and encrypt the individual characters, then spit that back out into a new string called encrypted_string. However, I cannot get this function to accept the argument passed into it. Any guidance?
This is where the program currently is:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
char substitution_cipher(string cipher_key, char char_to_encrypt);
char reverse_substitution_cipher(string cipher_key, char char_to_encrypt);
string EncryptString(string &cipher_key, string string_to_be_encrypted);
string DecryptString(string &cipher_key, string string_to_be_decrypted);
void RotateCipherKey(string &cipher_key);
void DisplayFile(string filename);
void EncryptFile(string cipher_key, string filename_from, string filename_to);
void DecryptFile(string cipher_key, string filename_from, string filename_to);
int main()
{
string cipher_key = "qwertyuiopasdfghjklzxcvbnm";
EncryptFile(cipher_key, "test.txt", "test-encrypted.txt");
DecryptFile(cipher_key, "test-encrypted.txt", "test-ed.txt");
DisplayFile("test.txt");
DisplayFile("test-encrypted.txt");
DisplayFile("test-ed.txt");
system("PAUSE");
return 0;
}
// Rotate the cipher key. Example: abcdef becames bcdefa
void RotateCipherKey(string &cipher_key)
{
rotate(cipher_key.begin(), cipher_key.begin() + 1, cipher_key.end());
}
// Perform a substitution cipher on a single character
// using the specified cipher key
char SubstitutionCipher(string cipher_key, char char_to_encrypt)
{
for (int iii = 0; iii < cipher_key.length(); iii++)
{
RotateCipherKey(cipher_key);
char_to_encrypt = cipher_key[iii];
}
return char_to_encrypt;
}
// Perform a "reverse" substitution cipher on a single character
// using the specified cipher key
char ReverseSubstitutionCipher(string cipher_key, char char_to_decrypt)
{
for (int iii = 0; iii < cipher_key.length(); iii++)
{
RotateCipherKey(cipher_key);
char_to_decrypt = cipher_key[iii];
}
return char_to_decrypt;
}
// Encrypt String and return it
// You will use the SubstitutionCipher() function to encrypt the
// individual characters
//
// Note: We will call RotateCipherKey() after each time we encrypt
// a character.
string EncryptString(string &cipher_key, string string_to_be_encrypted)
{
char *y = string_to_be_encrypted.c_str();
{
//SubstitutionCipher(cipher_key, string_to_be_encrypted);
}
cout << " " << string_to_be_encrypted;
string encrypted_string = string_to_be_encrypted;
return encrypted_string;
}
// Decrypt String and return it
// You will use the ReverseSubstitutionCipher() function to decrypt the
// individual characters
//
// Note: We will call RotateCipherKey() after each time we encrypt
// a character.
string DecryptString(string &cipher_key, string string_to_be_decrypted)
{
string decrypted_string = string_to_be_decrypted;
return decrypted_string;
}
// Display file specified by the filname parameter
void DisplayFile(string filename)
{
string str;
ifstream infile;
infile.open(filename);
infile >> str;
while (infile)
{
cout << " " << str;
infile >> str;
}
cout << endl;
}
// Encrypt the specified file using the specified cipher key and
// write the output to a different file
// This function is complete
void EncryptFile(string cipher_key, string filename_from, string filename_to)
{
string input;
ifstream infile;
ofstream outfile;
infile.open(filename_from.c_str());
outfile.open(filename_to.c_str());
if (!infile)
{
cout << "Can not open input file " + filename_from << endl;
exit(0);
}
if (!outfile)
{
cout << "Can not open Output file " + filename_to << endl;
exit(0);
}
while (getline(infile, input))
{
outfile << EncryptString(cipher_key, input) << endl;
}
infile.close();
outfile.close();
}
// Decrypt the specified file using the specified cipher key and
// write the output to a different file
// This function is complete
void DecryptFile(string cipher_key, string filename_from, string filename_to)
{
string input;
ifstream infile;
ofstream outfile;
infile.open(filename_from.c_str());
outfile.open(filename_to.c_str());
if (!infile)
{
cout << "Can not open input file " + filename_from << endl;
exit(0);
}
if (!outfile)
{
cout << "Can not open Output file " + filename_to << endl;
exit(0);
}
while (getline(infile, input))
{
outfile << DecryptString(cipher_key, input) << endl;
}
infile.close();
outfile.close();
}
EDIT//
string EncryptString(string &cipher_key, string string_to_be_encrypted)
{
char new_char;
for (int iii = 0; iii < string_to_be_encrypted.length(); iii++)
{
new_char = SubstitutionCipher(cipher_key, string_to_be_encrypted[iii]);
RotateCipherKey(cipher_key);
}
string encrypted_string = string_to_be_encrypted;
cout << " " << encrypted_string;
return encrypted_string;
}
Ok here is new code now with some modifications.
The problem you have is that c_str() returns a pointer to const, const char*, which you can not assign to a char* in the line
char* y=string_to_be_encrypted.c_str(); // cannot assign a `const char*` to `char*`
Use directly the string to perform your work. There is no other way of getting a pointer to non-const char to the data of a std::string.
Related
I'm currently trying to program a word counting program in C++ and am running into difficulties getting it to parse through a string and separate words from one another. In addition to this I am having a hard time getting the word count for unique words to increment each time the word repeats. My findWord() and DistinctWords() functions are most likely the issues from what I can tell. Perhaps you will see something I do not though in the others, as for the aforementioned functions I have no clue as to what's messing up in them. These are the directions provided by my instructor:
Create a program which will count and report on the number of occurrences of distinct, case insensitive words in a text file.
The program should have a loop that:
1.Prompts the user to enter a file name. Terminates the loop and the program if the user presses the Enter key only.
2.Verifies that a file with the name entered exists. If the file does not exist, display an appropriate message and return to step 1.
3.Reads and displays the contents of the file.
4.Displays a count of the distinct words in the file.
5.Displays a sorted list of each of the distinct words in the file and the number of occurrences of each word. Sort the list in descending order by word count, ascending order by word.
I am pretty stuck right now and my assignment is due at midnight. Help would certainly be greatly appreciated. Thank you for your time. Here is the code I have, I will also copy paste an example test text file after it:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream> // Needed to use files
#include <vector>
#include <algorithm> // Needed for sort from standard libraries
using namespace std;
struct WordCount{
string word; // Word
int count; // Occurence #
void iCount(){ count++; }
WordCount(string s){ word = s; count = 1;}
};
// Function prototypes
string InputText(); // Get user file name and get text from said file
string Normalize(string); // Convert string to lowercase and remove punctuation
vector<WordCount> DistinctWords(string); // Sorted vector of word count structures
bool findWord(string, vector<WordCount>); // Linear search for word in vector of structures
void DisplayResults(vector<WordCount>); // Display results
// Main
int main(int argc, char** argv) {
// Program Title
cout << "Lab 9 - Text File Word Counter\n";
cout << "-------------------------------\n\n";
// Input text from file
string buffer = InputText();
while (buffer != ""){
// Title for text file reading
cout << "\nThis is the text string read from the file\n";
cout << "-------------------------------------------\n";
cout << buffer << endl << endl;
// Build vector of words and counts
vector<WordCount> words = DistinctWords(buffer);
// Display results
cout << "There are " << words.size() << " unique words in the above text." << endl;
cout << "--------------------------------------------" << endl << endl;
DisplayResults(words);
buffer = InputText();
}
return 0;
}
/***********************************************
InputText() -
Gets user file name and gets text from the file.
************************************************/
string InputText(){
string fileName;
ifstream inputFile; // Input file stream object
string str; // Temporary string
string text; // Text file string
cout << "File name? ";
getline(cin, fileName);
// Case to terminate the program for enter key
if (fileName.empty()){ exit(0);}
// Open file
inputFile.open(fileName);
if (!inputFile){
cout << "Error opening data file\n";
cout << "File name? "; cin >> fileName;
}
else{
while (!inputFile.eof()){
getline(inputFile, str);
text += str;
}
}
inputFile.close(); return text;
}
/****************************************************
Normalize(string) -
Converts string to lowercase and removes punctuation.
*****************************************************/
string Normalize(string s){
// Initialize variables
string nString;
char c;
// Make all text lowercase
for (int i = 0; i < s.length(); i++){
c = s[i];
c = tolower(c);
nString += c;
}
// Remove punctuation
for (int i = 0; i < nString.length(); i++){
if (ispunct(nString[i]))
nString.erase(i, 1);
}
// Return converted string
return nString;
}
/******************************************
vector<WordCount> DistinctWords(string) -
Sorts vector of word count structures.
*******************************************/
vector<WordCount> DistinctWords(string s){
vector<WordCount> words; // Initialize vector for words
string nString = Normalize(s); // Convert passed string to lowercase and remove punctuation
// Parse string
istringstream iss(nString);
while(iss >> nString){
string n; // Intialize temporary string
iss >> n; // Put word in n
if (findWord(n, words) == true){ continue; } // Check to verify that there is no preexisting occurence of the word passed
else{
WordCount tempO(n); // Make structure object with n
words.push_back(tempO); // Push structure object into words vector
}
}
return words;
}
/*********************************************
bool findWord(string, vector<WordCount>) -
Linear search for word in vector of structures
**********************************************/
bool findWord(string s, vector<WordCount> words){
// Search through vector
for (auto r : words){
if (r.word == s){ // Increment count of object if found again
r.iCount(); return true;
}
else // Go back to main function if not found
return false;
}
}
/***********************************************
void DisplayResults(vector<WordCount>) -
Displays results.
************************************************/
void DisplayResults(vector<WordCount> words){
// TROUBLESHOOT FIRST ERASE THIS AFTER!!!!!
cout << "Word" << setw(20) << "Count\n";
cout << "-----------------------\n";
for (auto &r : words){
cout << setw(6) << left << r.word;
cout << setw(15) << right << r.count << endl;
}
}
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.
This is the example display he provided for this particular test file
You almost had it!
You just forgot to pass the 'words' vector by reference instead of by copy.
Also I included a custom comparator for the sort at the end.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <fstream> // Needed to use files
#include <vector>
#include <algorithm> // Needed for sort from standard libraries
using namespace std;
struct WordCount{
string word; // Word
int count; // Occurence #
void iCount(){ count++; }
WordCount(string s){ word = s; count = 1;}
};
struct {
bool operator()(const WordCount& a, const WordCount& b)
{
if (a.count < b.count)
return false;
else if (a.count > b.count)
return true;
else{
if (a.word < b.word)
return true;
else
return false;
}
}
} CompareWordCount;
// Function prototypes
string InputText(); // Get user file name and get text from said file
string Normalize(string); // Convert string to lowercase and remove punctuation
vector<WordCount> DistinctWords(string); // Sorted vector of word count structures
bool findWord(string, vector<WordCount>&); // Linear search for word in vector of structures
void DisplayResults(vector<WordCount>); // Display results
// Main
int main(int argc, char** argv) {
// Program Title
cout << "Lab 9 - Text File Word Counter\n";
cout << "-------------------------------\n\n";
// Input text from file
string buffer = InputText();
while (buffer != ""){
// Title for text file reading
cout << "\nThis is the text string read from the file\n";
cout << "-------------------------------------------\n";
cout << buffer << endl << endl;
// Build vector of words and counts
vector<WordCount> words = DistinctWords(buffer);
// Display results
cout << "There are " << words.size() << " unique words in the above text." << endl;
cout << "--------------------------------------------" << endl << endl;
DisplayResults(words);
buffer = InputText();
buffer = "";
}
return 0;
}
/***********************************************
InputText() -
Gets user file name and gets text from the file.
************************************************/
string InputText(){
string fileName;
ifstream inputFile; // Input file stream object
string str; // Temporary string
string text; // Text file string
cout << "File name? ";
getline(cin, fileName);
// Case to terminate the program for enter key
if (fileName.empty()){ exit(0);}
// Open file
inputFile.open(fileName);
if (!inputFile){
cout << "Error opening data file\n";
cout << "File name? "; cin >> fileName;
}
else{
while (!inputFile.eof()){
getline(inputFile, str);
text += str;
}
}
inputFile.close(); return text;
}
/****************************************************
Normalize(string) -
Converts string to lowercase and removes punctuation.
*****************************************************/
string Normalize(string s){
// Initialize variables
string nString;
char c;
// Make all text lowercase
for (int i = 0; i < s.length(); i++){
c = s[i];
c = tolower(c);
if (isalpha(c) || isblank(c))
nString += c;
}
// Return converted string
return nString;
}
/******************************************
vector<WordCount> DistinctWords(string) -
Sorts vector of word count structures.
*******************************************/
vector<WordCount> DistinctWords(string s){
vector<WordCount> words; // Initialize vector for words
string nString = Normalize(s); // Convert passed string to lowercase and remove punctuation
// Parse string
istringstream iss(nString);
string n; // Intialize temporary string
while(iss >> n){
if (findWord(n, words) == true){ continue; } // Check to verify that there is no preexisting occurence of the word passed
else{
WordCount tempO(n); // Make structure object with n
words.push_back(tempO); // Push structure object into words vector
}
}
return words;
}
/*********************************************
bool findWord(string, vector<WordCount>) -
Linear search for word in vector of structures
**********************************************/
bool findWord(string s, vector<WordCount>& words){
// Search through vector
for (auto& r : words){
if (r.word.compare(s) == 0){ // Increment count of object if found again
r.iCount(); return true;
}
}
}
/***********************************************
void DisplayResults(vector<WordCount>) -
Displays results.
************************************************/
void DisplayResults(vector<WordCount> words){
// TROUBLESHOOT FIRST ERASE THIS AFTER!!!!!
cout << "Word" << setw(20) << "Count\n";
cout << "-----------------------\n";
sort(words.begin(), words.end(),CompareWordCount);
for (auto &r : words){
cout << setw(6) << left << r.word;
cout << setw(15) << right << r.count << endl;
}
}
Consider using map for word count task
int main()
{
map<string, int> wordCount;
vector<string> inputWords = {"some", "test", "stuff", "test",
"stuff"}; //read from file instead
for(auto& s: inputWords)
wordCount[s]++; //wordCount itself
for(auto& entry: wordCount) //print all words and assosiated counts
cout << entry.first << " " << entry.second <<endl;
cout <<wordCount.size() <<endl; //thats number of distinct words
}
I'm currently beginning on C++ and trying to make a function that can open a .txt file, read it, and save its words in an array (each word being a protein sequence).
Unfortunately I don't succeed at calling the argument containing the name of the file (argv[1]) in the function.
Can anyone spot errors in my code or in the way I implemented this ?
Thanks in advance, you will find the code and the error messages below :
Libraries
So here are my librairies and 'shortcuts'.
// Librairies
#include <iostream>
#include <string>
#include <fstream>
// Alias
using std::cout;
using std::endl;
using std::string;
The function
Now this is the function, note that filename is supposed to be a string containing argv[1] (the name of a .txt file specified at execution) :
string SequenceChoice(int n, string filename); // Function returning a string
std::ifstream sequenceFile (filename); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}
sequenceFile.close();
cout<< "File closed"<<endl;
}
else
{
cout << "Error: Cannot open file" << endl;
}
return allchains[n]; // returns the 'n'th word (n being specified when calling the function
// end of the function
Main
Now the main function, I'm not sure if doing string filename = argv[1] works, but I get less errors when I keep this step instead of putting argv[1] as an argument of my SequenceChoice() function.
int main(int argc, char *argv[]) {
if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, filename ) << endl; // I expect it to give me the 3rd word of a .txt file for example.
}
else
{
cout << "Error : No file" << endl;
}
return 0;
}
The error message I get
Error message
The link above is a picture of the error message I get when I compile, I've been searching for hours on the internet how to resolve this, unfortunately I could'nt manage to have the code working. There's probably an error of type with the way I deal with argv[], but I failed at solving it so any help and comments would be greatly appreciated.
Please try changing following line
string SequenceChoice(int n, string filename); // Function returning a string
to
string SequenceChoice(int n, string filename) { // Function returning a string
You are trying to write a function but the ; is terminating your function and body is not starting. It should work. Also please read a book carefully.
This page lists very good books for all experience levels.
Try this :
string SequenceChoice(int n, string filename)
{
std::ifstream sequenceFile (filename); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}
ifs.close();
cout<< "File closed"<<endl;
}
else
{
cout << "Error: Cannot open file" << endl;
}
return allchains[n];
}
Here is fully functioning code:
You can compare it with yours.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string SequenceChoice(int n, string filename){ // Function returning a string
std::ifstream sequenceFile (filename); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}
sequenceFile.close();
cout<< "File closed"<<endl;
return allchains[n]; // returns the 'n'th word (n being specified when calling the function
}
else
{
cout << "Error: Cannot open file" << endl;
}
return NULL;
// end of the function
}
int main(int argc, char *argv[])
{
if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, filename ) << endl; // I expect it to give me the 3rd word of a .txt file for example.
}
else
{
cout << "Error : No file" << endl;
}
}
Thanks to your answers I managed to solve my problem, apart from some syntax errors in the code the argument filename in the function was a string, and as argv[] is an array of pointers. So it just couldn't work to consider them as the same type.
Here is a working version of the function, for those it could help :
string SequenceChoice(int n, char* argv[])
{
std::ifstream sequenceFile (argv[1]); //Opens the file specified on execution
if ( sequenceFile.is_open() )
{
cout<< " .File opened. \n" <<endl;
string tmp;
int i = 0;
while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}
cout << " " << i << " chains in the .txt file : \n" << endl;
string allchains[i]; // Creates an array of strings, to save all the words
sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;
while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << " --- Chain "<< i + 1 << " --- : " << allchains[i] << endl;
i++;
}
sequenceFile.close();
cout << "\n .File closed. \n" << endl;
return allchains[n];
}
else
{
cout << "Error: Cannot open file" << endl;
return NULL;
}
}
And finally the new main function :
int main(int argc, char *argv[]) {
if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, argv ) << endl; // Shows the 3rd word of the file, as an example.
}
else
{
cout << "Error : No file" << endl;
}
return 0;
}
Thanks for your help and have a great day !
I'm using a simple encryption that I found online. Basically, I'm streaming in a file, checking to see if that file is open (if not, display an error message) and putting each line in each element of the array while encrypting the information. Afterwards I stream that encrypted information onto an output file.
However, I'm getting nothing in my output.txt file. The encryption works fine if you test it by itself.
Here is my code:
#include <string>
#include <fstream>
#include <sstream> // for ostringstream
#include <iostream>
#include <stdio.h>
#include <algorithm>
/* Credits to kylewbanks.com */
string encrypt (string content) {
char key[3] = {'K'}; //Any chars will work
string output = content;
for (int i = 0; i < content.size(); i++)
output[i] = content[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
int main() {
string input, line;
string content[10000];
string encryptedContent[10000];
int counter = 0, innerChoice = 0, i, finalCounter;
cout << "\tPlease enter the file name to encrypt!\n";
cout << "\tType '0' to get back to the menu!\n";
cout << "Input >> ";
cin >> input;
/* Reads in the inputted file */
ifstream file(input.c_str());
//fopen, fscanf
if(file.is_open()) {
/* Counts number of lines in file */
while (getline(file, line)) {
counter++;
}
cout << counter;
finalCounter = counter;
for (i = 0; i < finalCounter; i++) {
file >> content[i];
encryptedContent[i] = encrypt(content[i]);
cout << encryptedContent[i];
}
} else {
cout << "\tUnable to open the file: " << input << "!\n";
}
/* Write encryption to file */
ofstream outputFile("output.txt");
for (i = 0; i < finalCounter ; i++) {
outputFile << encryptedContent;
}
outputFile.close();
}
Any clue what is wrong?
string content[10000];
string encryptedContent[10000];
This is wrong because it is creating 20000 strings (you probably think it is creating a large enough character array to read the data).
string content; is enough. It can be resized to handle any length of strings.
You just need to read/write the file in binary:
int main()
{
string input = "input.txt";
ifstream file(input, ios::binary);
if (!file.is_open())
{
cout << "\tUnable to open the file: " << input << "!\n";
return 0;
}
string plaintext;
//read the file
file.seekg(0, std::ios::end);
size_t size = (size_t)file.tellg();
file.seekg(0);
plaintext.resize(size, 0);
file.read(&plaintext[0], size);
cout << "reading:\n" << plaintext << "\n";
//encrypt the content
string encrypted = encrypt(plaintext);
//encrypt again so it goes back to original (for testing)
string decrypted = encrypt(encrypted);
cout << "testing:\n" << decrypted << "\n";
/* Write encryption to file */
ofstream outputFile("output.txt", ios::binary);
outputFile.write(encrypted.data(), encrypted.size());
return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void read();
int main() {
read();
return 0;
}
void read () {
string file("");
string nameOfFile("");
cin >> nameOfFile;
ifstream in (nameOfFile);
while ( !in.eof() ) {
getline(in, file);
cout << file;
cout << endl;
}
cout << file;
in.close();
}
How come this isn't working, I'm trying to make it so i can type in which file i want to read?
I'm really new to C++, sorry if this is an obvious fix.
You have to change
ifstream in (nameOfFile);
with
ifstream in (nameOfFile.c_str());
because the default constructor for ifstream does not accept a std::string as an argument, it needs a char *. Hence, use the function std::string::c_str() to convert a std::string into a char *.
A little feedback:
void read () {
string file(""); // you don't need the ("") bit; empty by default,
// and "file" is a terrible choice of identifier as
// it sounds more like an ifstream than a string
// used to hold one line from the file.
// I tend to use "string line;" for this.
string nameOfFile(""); // ditto
cin >> nameOfFile; // you should test for success of input, like this:
// if (!cin >> nameOfFile) {
// std::cerr << "error reading filename from stdin\n";
// exit(1);
// }
ifstream in (nameOfFile); // test for success getting file open like this:
// if (ifstream in(nameofFile))
// {
while ( !in.eof() ) { // NEVER check eof before attempting input, instead:
getline(in, file); // while (getline(in, file))
cout << file; // cout << file << endl; // can "chain"
cout << endl; // }
// else
// std::cerr << "couldn't open " << nameOfFile
// << '\n';
} // no need for extra cout nor explicit close, as
cout << file; // the ifstream destructor closes anyway.
in.close();
}
You need to open the ifstream usign in.open(), and hendle the case where file does not exist as well. here is the function:
void read() {
string file("");
string fileContent = "";
string nameOfFile("");
cin >> nameOfFile;
ifstream in(nameOfFile.c_str());
in.open(nameOfFile, ios::in);
if (in){
while (!in.eof()) {
getline(in, file);
fileContent += file;
}
cout << fileContent;
in.close();
}
else {
cout << "Could not open file.";
}
}
The code I have loads a encrypted text file, with the first line of this text file being a cipher that is used to decode the rest of the text file. I know that this error usually happens if the function isn't defined before main, but I have it defined in the header, so i'm not sure what is causing this problem.
#include <string>
#include <iostream>
#include <fstream>
std::string decrypt(std::string cipher, std::string text);
int main()
{
//variable
std::string fileName;
std::string cipher;
std::string text;
//prompt the user to enter the file name
std::cout << "Enter file name: ";
std::cin >> fileName;
//declare input stream
std::ifstream inFile(fileName);
//Checks if the file has been connected or not
if (inFile.is_open())
{
std::cout << "File found." << std::endl;
std::cout << "Processing..." << std::endl;
getline(inFile,cipher); //get the first line as one string
std::cout << cipher << std::endl; //TEST!!!!
std::cout << "\n" << std::endl; //TEST!!!!!!
while (inFile.good()) //continue running until an error occurs to get the rest of the text as second string
{
getline(inFile,text); //get the first line as one string
std::cout << text << std::endl; //TEST!!!!
}
}
else //if the file isn't connected
{
std::cout << "File not found." << std::endl; **(ERROR C3861 HERE)**
}
inFile.close(); //close the file
std::string finalResult = decrypt(cipher,text);
std:: cout << finalResult << std::endl;
return 0;
}
//Decrypt function: Takes 2 strings by reference, changes the second string into the unencrypted text
std::string decrypt(std::string cipher, std::string text)
{
char alphabet[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //create a character array of the alphabet
char code[27]; //empty array
char oldText[500]; //empty array
strcpy(code,cipher.c_str()); //copies the cipher into the array
strcpy(oldText,text.c_str()); //copies the encrypted text into the array
for (int i = 0; i < 500;i++) //Loop through the entire encrypted text
{
int k = i; //creates and resets a variable for while loop
while (alphabet[k] != oldText[i])
{
k = k+1;
}
oldText[i] = alphabet[k]; //after a match is detected, swap the letters
}
std::string newText(oldText); // converts the array back into text
return newText;
}
Your problem is this line in decrypt:
std::string text(oldText); // converts the array back into text
It does not convert 'oldText' back into text; instead it declare a new local variable named test. That new local variable conflicts with the parameter named text. This is the line that is causing the C2082. What you should have written is:
text = oldText;
Which is replace the contents of test with what is in oldText Although it would be simpler to skip that entirely and just return oldText.
I don't get a C3861 when compling your code, plus the fact that you are showing the C2082 on the wrong line makes me think your source file is out of sync with your errors.