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.
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 !
This program takes in an input, write it on a file character by character, count the amount of characters entered, then at the end copy it to an array of characters. The program works just fine until we get to the following snippet file.getline(arr, inputLength);. It changes the .txt file data and returns only the first character of the original input.
Any ideas?
#include <iostream>
#include <fstream>
using namespace std;
int getLine(char *& arr);
int main() {
char * arr = NULL;
cout << "Write something: ";
getLine(arr);
return 0;
}
int getLine(char *& arr) {
fstream file("temp.txt");
char input = '\0'; //initialize
int inputLength = 0; //initialize
if (file.is_open()) {
while (input != '\n') { //while the end of this line is not reached
input = cin.get(); //get each single character
file << input; //write it on a .txt file
inputLength++; //count the number of characters entered
}
arr = new char[inputLength]; //dynamically allocate memory for this array
file.getline(arr, inputLength); //HERE IS THE PROBLEM!!! ***
cout << "Count : " << inputLength << endl; //test counter
cout << "Array : " << arr << endl; //test line copy
file.close();
return 1;
}
return 0;
}
I see at least two problems with this code.
1) std::fstream constructor, by default, will open an existing file. It will not create a new one. If temp.txt does not exist, is_open() will fail. This code should pass the appropriate value for the second parameter to std::fstreams constructor that specifies that either a new file needs to be created, or the existing file is created.
Related to this: if the file already exists, running this code will not truncate it, so the contents of the file from this program's previous run will have obvious unexpected results.
2) The intent of this code appears to be to read back in the contents temp.txt that were previously written to it. To do that correctly, after writing and before reading it is necessary to seek back to the beginning of the file. This part appears to be missing.
There is no need in dynamic allocation because the std library functions get confused with mixed arguments such as cstring and pointer to cstring.I tested this code in Visual Studio 2015 compiler. It works good. Make sure to include all of the needed libraries:
#include <iostream>
#include <fstream>
#include<cstring>
#include<string>
using namespace std;
void getLine();
int main() {
cout << "Write something: ";
// no need to pass a pointer to a cstring
getLine();
system("pause");
return 0;
}
void getLine() {
char input[100]; // this is a cstring with
//a safe const number of elements
int inputLength; //to extract length of the actual input
//this function requires cstring as a first argument
// and constant length as a second
cin.get(input, 100, '\n'); //get each single character
//cast streamsize into int
inputLength = static_cast<int>(cin.gcount());
//testing input
cout << "Input: \n";
for (int i = 0; i < inputLength; i++)
{
cout << input[i];
}
cout << endl;
char arr[100];
strcpy_s(arr, input);
cout << "Count : " << inputLength << endl; //test counter
cout << "Array : " << endl; //test line copy
for (int i = 0; i < inputLength; i++)
{
cout << arr[i];
}
cout << endl;
// write cstring to a file
ofstream file;
file.open("temp.txt", ios::out);
if (file.is_open())
{
//write only what was entered in input
for (int i = 0; i < inputLength; i++)
file << arr[i];
file.close();
}
else cout << "Unable to open file";
}
I have coded a programm which can load one text file, can decide how long each word is and can write txt files based on the length of the words. But when i run the programm, the new text files are always filled with just one word(each new word with an already existing text file for his length just overrides the text file)
The start text file looks like this():
http://i.stack.imgur.com/WBaRf.png
My new created text files(named after their length for example: 7.txt) after i runned the programm:
http://i.stack.imgur.com/6QKgE.png
My code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
char filename[128];
ifstream file;
char line[100];
cout << "Input filename: " << flush;
cin.getline(filename, 127);
file.open(filename, ios::in);
if (file.good())
{
file.seekg(0L, ios::beg);
int number = 0;
while (!file.eof())
{
file.getline(line, 100);
stringstream stream;
stream << line;
number++;
cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
std::stringstream sstm;
int laenge = stream.str().length();
string txt = ".txt";
sstm << laenge << txt;
string result = sstm.str();
std::ofstream outFile(result);
outFile << line << endl;
outFile.close();
}
}
else
{
cout << "File not found" << endl;
}
while (true)
{
};
return 0;
}
My goal is that i have sorted the whole words into the file their files, the only problem is that they overwrite themself... How can i get rid off that?
If you don't want to overwrite the content of the file, you can open the file and specify that you want to append to the file:
std::ofstream outFile(result, ios::app);
// ^^^^^^^^
I am currently working on a project that converts a .txt file into a .xhtml file using the command line properties. Specially, this program converts an ASCII text file to an xhtml 1.0 file containing the same textual content as the original ASCII text file. The problem I seem to have is when I open the .html file to read the content from the old .txt file only one word from the file is being read into the html file. Can anyone explain why this is so? The help would be much appreciated.Thank you in advance.
//Programmer:
//Date: March 9 2015
//Purpose: converts an old style text file into any format
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <map>
using namespace std;
// getWord function to read in all words
istream& getWord(istream& is, string& word)
{
// find the beginning of the word (ie . eat all the non alphas)
char ch;
while (is.get(ch))
{
if (isalpha(ch))
break;
}
// quit if no word found
if (!is)
return is;
string buffer;
buffer += ch; // put the valid alpha onto the buffer
while (is.get(ch))
{
if (isalpha(ch))
buffer += ch;
else
break;
}
if (is)
is.unget();
if (is.eof())
is.clear();
if (is)
//word = buffer; // put the complete buffer into the word so it can be returned by reference.
//This does a copy + destroy!!
swap(word, buffer); // C++98(swap owner, then destory the old)
word = std::move(buffer); // C++ 11
return is;
}
int main(int argc, char* argv[])
{
ifstream infile(argv[1]);
char ch = 0;
while (infile.get(ch)){
cout.put(ch);
}
// print out all the command line arguments
for (size_t i = 0; i < argc; ++i)
{
string s = (string)argv[i];
cout << s << endl;
}
//if input file is at location 1 in the command line
string input = argv[1];
for (size_t i = 0; i < input.size(); ++i)
{
cout.put(input[i]);
}
cout << endl;
// Creating the html output file
ofstream out("title.html");
out << "<html xmlns=\"http://www.w3.org/1999//xhtml\"xml:lang=\"en\">" << endl;
out << "<head>" << endl;
out << "<meta http - equiv = \"Content-Type\" content = \"text/html; charset=UTF-8\" />" << endl;
out << "<title>" << argv[1] << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << argv[1] << endl;
// extracting the words from the file and storing it in a container
typedef map<string, unsigned> dictionary_type;
dictionary_type words;
// read the information in to find only words
string word;
while (getWord(infile, word))
{
auto loc = words.find(word);
if (loc == words.end())
words.insert(pair<string, int>(word, 1));
else
loc->second++;
}
//print out the container
for (auto w : words)
cout << w.first << ": " << w.second << endl;
out << "</body>" << endl << "</html>";
}
I see couple of problems:
You are reading the contents of the file first, echoing the contents to std::cout. After you are done with that, there is nothing to read from the file. Add a call to rewind the file and then read its contents again.
infile.clear(); // Clear its state. Otherwise infile.eof() is true.
infile.seekg(0); // rewind
Those lines need to go before
while (getWord(infile, word))
You have the lines:
if (is)
swap(word, buffer); // C++98(swap owner, then destory the old)
word = std::move(buffer); // C++ 11
You need to use only one of them, not both. If you use both, word gets set to an empty string.