Word Counting Program C++ - c++

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
}

Related

Output whole sentence when reversing words in string c++

Have to create our own function that receives a sentence/sentences from an input file. It then should reverse the letters of each word individually and leaves all other (non-alphabetic) characters in the plaintext unchanged i.e "The cat sat on the mat!" will become
"ehT tac tas no eht tam!".
So I think I have found a way to reverse words individually but don't know how to find a way to output everything in one sentence. I feel like I would need to somehow use arrays or vectors to help store each word, and then output all the words together at the end, but I have not been successful.
I also want to find a way for it to know when to stop and to output the blank spaces between words.
Here is my code so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void reverse(string input);
int main(){
ifstream inData;
ofstream outData;
string input;
inData.open("input.txt");
outData.open("output.txt");
while(getline(inData, input)){
// cout << input;
outData << input;
}
reverse(input);
inData.close();
outData.close();
return 0;
}
void reverse(string input){
int counter =0;
while(counter != 14){
int idx = input.find(" ");
cout << idx << endl;
string word = input.substr(0, idx);
cout << word << endl;
string x;
for (int i = idx-1; i >= 0; i--)
{
x= word.at(i);
cout << x;
}
cout << endl;
input.erase(0,idx+1);
cout << input << endl;
cout << endl << "new" << endl;
counter++;
}
}
So here is code that can output the sentence from the input file, with each word being reversed and all these words then being outputted in one sentence in the order they were in the sentence. There is still some problems to it, like if there is a non-alphabetic character in the word, at the front or somewhere before the end, that character will be pushed to the back of the word, so this needs to be improved on. Feel free to nicely add constructively criticism if have any. However, think this still provides for the original question. Thank you all for the help.
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void reverse(string input);
int main(){
ifstream inData;
ofstream outData;
string input;
inData.open("input.txt");
outData.open("output.txt");
while(getline(inData, input)){ //get sentence from input line
reverse(input); //Reverse the sentence
cout << endl; //end line for next sentence
}
inData.close();
outData.close();
return 0;
}
void reverse(string input){
string nonAlpha = "";
bool end = false;
bool nonLetter = true;
while(end != true){
int idx = input.find(" "); //Finds index of blank space
int lastIdx = input.size(); //Finds the last index
if(idx <= 0){ //If it is the last index, then that becomes idx
idx = lastIdx;
end = true;
}
string word = input.substr(0, idx); //Word usually starts from index 0, until the blank space
string x;
for (int i = idx-1; i >= 0; i--){ //Then outputs each letter according to the index of the word
// but starts from last index and decrements thereby reversing the word
if((isalpha(word.at(i))==false)){ //If that index is not a letter then it is stored and will be outputted after word
nonAlpha.push_back(word[i]); //However this can be a problem for non-letter if not at end of word
nonLetter = true;
}
else{
x= word.at(i);
cout << x; //Prints the letter
}
}
if(nonLetter == true){
cout << nonAlpha; //Prints the non-letter
nonAlpha.erase(); //Erases whatever is inside for future non-letters
nonLetter = false; //Makes it false and will be used agaian when there is another non-letter
}
cout << " "; //Space between words
input.erase(0,idx+1); //Erases word when finished reversing and outputting it so can start next word
}
}

How I do split a string into 2 different variables (string and integer) at a certain point? C++

My program receives input from the user, in this exact form: string, integer. An example would be: Brady, 12. I need to split the string at the comma, and store the first part into a vector of strings, and the 2nd part into a vector of integers. How do I go about this? (Sorry, I'm very new to programming)
This is what my code currently looks like:
while(true) {
cout << "Enter a data point (-1 to stop input): " << endl;
getline(cin, dataPoint);
if (dataPoint == "-1") { //Ends Program
break;
}
if (dataPoint.find(",") == std::string::npos) {
cout << "Error: No comma in string." <<endl;
}
}
We wouldn't normally write your code for you, but I'm going to offer a few hints.
First, storing the data the way you're going to do is probably the wrong approach, unless it's required for your homework. I'd keep it related:
class Person {
... various methods
private:
std::string name;
int age;
}
I would parse the data into one of these and store THAT into a std::vector<Person>. That keeps your data together.
As for splitting the string:
size_t pos = str.find(",");
if (pos == string::npos) {
... no comma found
}
else {
string name = str.substr(0, pos);
string ageStr = str.substr(pos + 1);
}
There's more you have to do, of course, but that's how you can divide the string into two pieces.
Here is the solution:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout << "Enter a data point (-1 to stop input): " << endl;
string input;
getline(cin, input);
if (input == "-1") return 0;
int comma = input.find(","); //find separator
string name = input.substr(0, comma); //find name and nuber using this number
string snumber = input.substr(comma + 2); // comma itself and space
cout << "The name is: " << name << " The number is: " << snumber << endl;
int number = stoi(snumber); //switch string to int
vector<string> names;
vector<int> numbers;
names.push_back(name); // add to vector
numbers.push_back(number);
return 0;
}

C++: Hangman game

I'm in the process of writing the program and stumbled upon a few issues.
The code reads a text file, which contains a list of 20 string words. The function playHangman() is supposed to read the file and randomly picks one word, which is displayed as asterisks in the console. The code works fine with local words when the function is called. For example Playhangman("stackOverflow"), will show the exact number of characters and will loop through them until the word is guessed right. If you take a look at the code, I'm calling the random word into the function. That word is stored as array. I know that that's not the proper way to do randomize, but for now, even if it picks the same word over and over, that's Ok, I just need to make sure it actually reads the array. The other thing is, when all characters are revealed, all the words on that text file are displayed, looks like I'm calling the entire content of the array instead of just that random word that's supposed to be generated.
Any help would be appreciated, thank you!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string word[20];
string randomWord = word[rand() % 20];
int playHangman(string randomWord) {
int misses = 0;
int revealedletters = 0;
string display = randomWord;
ifstream textFile;
// Open file
textFile.open("hangman.txt");
// Check if file exists
if (!textFile) {
cerr << "Unable to open text file\n";
exit(1); // Call system to stop
}
else {
cout << "File opened successfully. Program will continue...\n\n";
// Loop through the content of the file
while (textFile >> randomWord) {
for (int i = 0; i < display.length(); i++)
display[i] = '*';
while(revealedletters < randomWord.length()) {
cout << "Misses: " << misses << endl;
cout << "Enter a letter in word ";
cout << display << " : ";
char response;
cin >> response;
bool goodGuess = false;
bool duplicate = false;
for (int i = 0; i < randomWord.length(); i++)
if (response == randomWord[i]) {
if (display[i] == randomWord[i]) {
cout << response << " is already in the word." << endl;
duplicate = true;
break;
}
else {
display[i] = randomWord[i];
revealedletters++;
goodGuess = true;
}
}
if (duplicate)
continue;
if (!goodGuess) {
misses++;
cout << response << " is not in word\n";
}
}
cout << "You guessed right! The word is " << randomWord << ".\n";
}
return misses;
}
}
// TODO: Do you want to guess another word, Y/N?
int main () {
playHangman(randomWord);
// TODO: number of misses to guess the word.\n";
}
In your declaration and initialisation of your global variables:
string word[20];
string randomWord = word[rand() % 20];
word is an array of 20 empty strings and therefore randomWord will also always be empty.
In your playHangman function you have:
while (textFile >> randomWord) {
for (int i = 0; i < display.length(); i++)
display[i] = '*';
while(revealedletters < randomWord.length()) {
......
This reads a single word from the file into randomWord, plays the game with that word then loops round to read the next word and plays again with that word. As revealedletters doesn't get reset the game will finish immediately if the first word is longer than the next one.
I think the code you actually want looks something like this (remove your global variables too):
std::string word;
std::vector<std::string> words;
while (textFile >> word) {
words.push_back(word);
}
randomWord = words[rand() % words.size()];
std::string display = std::string(randomWord.size(), '*');
while(revealedletters < randomWord.length()) {
......
If you really must use arrays:
const size_t maxWords = 20;
std::string words[maxWords];
size_t wordCount = 0;
while (textFile >> word && wordCount < maxWords) {
words[wordCount++] = word;
}
randomWord = words[rand() % wordCount];
std::string display = std::string(randomWord.size(), '*');
while(revealedletters < randomWord.length()) {
......

Why is it only printing one word of the text file rather than the whole text file to a html file

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.

Reading information into array of structs c++

I'm making a program for my c++ class. Ultimately I want my program to perform a quicksort on a text file of contacts in the following format:
Firstname Secondname Number
Each contact is separated by a new line. I've started by counting the number of lines and using dynamic memory allocation to create an array of structs which has the same size as the number of lines.
However, when I tried to read in the information from the text file and output it to the screen, all I get is gibberish. I've had a look around on the internet to try and find a solution but everything I've found seems to use a different syntax to me.
Here's my code so far:
#include <iostream>
#include <fstream>
#include <istream>
char in[20];
char out[20];
using namespace std;
struct contact
{
char firstName[14];
char surName[14];
char number[9];
};
//structure definition
int main(void){
cout << "Please enter the input filename: " << endl;
cin >> in;
ifstream input(in);
if(!input){
cerr << "failed to open input file " << in << endl;
exit(1);
}
cout << "Please enter tne output filename: " << endl;
cin >> out;
// read in the input and output filenames
char a;
int b=0;
while (input.good ())
{
a=input.get ();
if (a=='\n')
{
b++;
}
}
// count the number of lines in the input file
input.seekg (0, ios::beg);
//rewind to beginning of file
contact* list = new contact[b];
//dynamically create memory space for array of contacts
int i = 0.;
while(input){
if(i >= b) break;
if(input >> *list[i].firstName >> *list[i].surName >> *list[i].number) i++;
else break;
}
input.close();
//read information from input file into array of contacts
for(int N = 0; N < b; N++){
cout << list[N].firstName << list[N].surName << list[N].number << endl;
}
ofstream output(out);
int k = 0;
for(int k = 0; k<b; k++){
output << list[k].firstName << " " << list[k].surName << " " << list[k].number << endl;
}
//print out the unsorted list to screen and write to output file
//i've done both here just to check, won't print to screen in final version
output.close();
delete []list;
} // end of main()
You reset the files location to the beginning, but the files eofbit is still labeled as true from when you first read the amount of lines. A quick fix to this is re-opening the file after you read the lines, possibly making the line count a function to clean up code.
int lines(const string path)
{
ifstream tmp(path.c_str());
string temp;
int count = 0;
getline(inFile,temp);
while(inFile)
{
count++;
getline(inFile,temp);
}
tmp.close();
return count;
}
Okay, I put together a quick and dirty method using newer C++ constructs to get you most of the way there. You're on your own for writing to the file (trivial) and the quicksort, though I've put the struct into a vector for you, so sorting the vector is as easy as writing a custom function to compare one struct vs the other. I apologize in advance if some of the code is less than canonical C++. I'm way past my bed time, and way tired, but this was interesting enough of a problem that I wanted to give it a go. Happy coding!
#include <iostream>
#include <fstream>
#include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace std;
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
}
struct contact
{
std::string firstName;
std::string surName;
std::string number;
contact(std::string& fName, std::string& lName, std::string& num) : firstName(fName), surName(lName), number(num) {}
};
//structure definition
char in[20];
char out[20];
int main()
{
std::vector<contact> contacts;
cout << "Please enter the input filename: " << endl;
cin >> in;
ifstream input(in);
if(!input){
cerr << "failed to open input file " << in << endl;
exit(1);
}
cout << "Please enter tne output filename: " << endl;
cin >> out;
std::string sinput;
// read in the input and output filenames
while (input.good ())
{
getline(input, sinput);
vector<string> tokens = split(sinput, ' ');
if (tokens.size() == 3)
{
contact c(tokens[0], tokens[1], tokens[2]);
contacts.push_back(c);
}
}
input.close();
//read information from input file into array of contacts
std::cout << "Outputting from vector..." << std::endl;
for_each(contacts.begin(), contacts.end(), [](contact& c) {
cout << c.firstName << " " << c.surName << " " << c.number << endl;
});
return 0;
}
Also, just want to give credit that the split methods come from this answer on this very site. Cheers!