Removal malfunction - c++

I have created a function that reads from a text file, adds content to a vector, shows the contacts. Then it prompts the user to choose which contact to remove. The program removes the contact but it removes other contacts as well (not all of them).
Here is the code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdio>
#include <iomanip>
using namespace std;
vector<string> contakt;
void deleteContact()
{
ifstream input;
input.open("contacts.txt");
string entry;
int contactID=0;
int index = contactID;
while (getline(input, entry))
{
contakt.push_back(entry);
}
input.close();
cout << "\n\n\nCurrent contacts in list: "<< endl;
if (contakt.size() == 0) cout << "Empty" <<endl;
for (int i = 0; i < contakt.size(); i++)
{
cout << i << ") " << contakt[i] << endl;
}
cout<< " Enter the Id of the contact you would like to remove"<<endl;
cin>> contactID;
if (index != -1)
{
ofstream output;
output.open("temp.txt");
for (vector<string>::iterator it = contakt.begin(); it!= contakt.end(); it++)
{
contakt.erase(contakt.begin() + index);
output<< *it <<'\n';
}
remove("contacts.txt");
rename("temp.txt", "contacts.txt");
output.close();
cout << "Contact deleted succesfull." << endl;
}
else cout << "\nNote: Id was not found in file." <<endl;
return;
}
code here
I remade the function from the beggining and now i am facing another problem.
At the end of the file a blank space is created whenever i remove a contact.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void deleteContact()
{
vector<string> file;
string temp;
ifstream input("contacts.txt");
while( !input.eof() )
{
getline(input, temp);
file.push_back(temp);
}
input.close();
string item;
cout << "Enter an name to delete from the contacts: ";
cin>>item;
int t = 0;
for(int i = 0; i < (int)file.size(); ++i)
{
if(file[i].substr(0, item.length()) == item)
{
file.erase(file.begin() + i);
cout << "Order erased!"<< endl;
i = 0; // Reset search
t++;
}
}
if (t == 0) cout<< "There is no contact with that name!!"<< endl;
ofstream output("contacts.txt", ios::out | ios::trunc);
for(vector<string>::const_iterator i = file.begin(); i != file.end(); ++i)
{
output << *i << '\n';
}
output.close();
return;
}

Your code modifies the vector while it iterates over it.
This invalidates the iterator.
Retrieve the updated iterator returned from the erase() function.
More details here: iterate vector, remove certain items as I go
Or, as you seem to delete just one contact at a time, just break your for loop after the first call to erase.

Related

For loop returning process after 2nd iteration

I'm writing code to take a player's name as input, search a csv file for the name and if the file contains the name save the entire row to a vector within a vector to be accessed later. However the process is returned after the 2nd iteration of the for loop (it's supposed to loop 11 times). Any help is appreciated! Here's the code:
[#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include "fantasy.h"
using namespace std;
player::player(void)
{
NULL;
}
void player::playerinput(void)
{
playername = " ";
playern2 = " ";
int count = 0;
fileName = " ";
for(int i=0; i<11; i++){
std::cout << "Enter player second name: ";
std::cin >> playername;
player::opencsv(playername);
}
}
void player::opencsv(string playername){
count = 0;
run = true;
string line, word, temp;
vector<string> row = {};
fin.open("C:/Users/Desktop/CSProject/cleaned_players 1819.csv", ios::in);
while(run){
row.clear();
getline(fin, line);
stringstream s(line);
while (getline(s, word, ',')){
row.push_back(word);
}
playern2 = row\[1\];
if(playern2 == playername){
count = 1;
players.push_back(row);
std::cout << "Player: " << row\[0\] << " " << row\[1\] << " added to database" << std::endl;
run = false;
return;
}
if(count = 0){
std::cout << "Player not in database" << std::endl;
return;
}
}
row.clear();
fin.clear();
}
int main()
{
player P1;
P1.playerinput();
}
1

For each distinct word in the file, display a count of the number of times that word appears in the file

This is one of my homework and I keep running into seg fault after the cin while loop, can anybody tell what did I do wrong? I have not learn map yet so I can't do that. One of my thought is that it went into seg fault because I was comparing the two string elements inside the vector, what is the way to do that properly?
#include <chrono>
#include <climits>
#include <cfloat>
#include <limits>
#include <cassert>
#include <exception>
#include <cctype>
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <regex>
#include <vector>
using namespace std;
int main()
{
vector<string> word_input;
vector<int> word_count;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
while (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
if (word != word_input.back())
{
word_input.push_back(word);
word_count.push_back(1);
}
else
{
word_count.push_back( word_count.back() + 1);
}
}
int count =word_count.back();
// Compare the input words
// and output the times of every word compared only with all the words
for (int i = 0; i != count; ++i)
{
int time = 0;
for (int j = 0; j != count; ++j)
{
if (word_input[i] == word_input[j])
++time;
}
std::cout << "The time of "
<< word_input[i]
<< " is: "
<< time
<< endl;
}
inputFile.close();
return 0;
}
The strategy you are using is fraught with problems. A simpler approach would be to use a std::map<std::string, int>.
int main()
{
std::map<std::string, int> wordCount;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
if (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
// --------------------------------------------------------------
// This is all you need to keep track of the count of the words
// --------------------------------------------------------------
wordCount[word]++;
}
for ( auto const& item : wordCount )
{
std::cout << "The time of "
<< item.first
<< " is: "
<< item.second
<< std::endl;
}
inputFile.close();
return 0;
}

beginner :While loop not working as it should

I am still a beginner and I am learning from a book. There was a drill that asked me filter input based on a vector of filtered words and if it was one of them it outputs "bad word"
Here is the drill exactly as in the book.
Try This
Write a program that “bleeps” out words that you don’t like; that is, you read in words using cin and print them again on cout. If a word is among a few you have defined, you write out BLEEP instead of that word. Start with one “disliked word” such as string disliked = “Broccoli”
When that works, add a few more.;
Here is the code I wrote:
#include <D:\std_lib_facilities.h>
int main()
{
// RL: omitting actual "bad" words to protect the innocent...
vector <string> bwords { "word1", "word2", "word3" };
vector <string> words;
string input = "";
while(cin >> input)
{
words.push_back(input);
}
double counter1 = 0;
double counter2 = 0;
while(counter1 < bwords.size() && counter2 < words.size())
{
if(bwords[counter1] == words[counter2])
{
cout << " bad word ";
}
else if (counter1 == bwords.size() - 1 && counter2 != words.size() )
{
cout << " "<< words[counter2] <<" ";
counter1 = 0;
}
else
{
++counter1;
counter2 += 1 / bwords.size();
}
}
}
whenever it starts it just tests the first word and repeats its self as if just tests the first if condition.
You over-complicated your loop. Try something more like this instead:
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// RL: omitting actual "bad" words to protect the innocent...
const vector <string> bwords { "word1", "word2", "word3" };
string bleepWordIfBad(const string &word)
{
if (std::find(bwords.begin(), bwords.end(), word) != bwords.end())
return "BLEEP";
else
return word;
}
int main()
{
vector <string> words;
string input;
while (cin >> input)
words.push_back(input);
for (int counter = 0; counter < words.size(); ++counter)
cout << " " << bleepWordIfBad(words[counter]) << " ";
/*
Alternatively:
for (vector<string>::iterator iter = words.begin(); iter != words.end(); ++iter)
cout << " " << bleepWordIfBad(*iter) << " ";
*/
/*
Alternatively:
for (const string &word : words)
cout << " " << bleepWordIfBad(word) << " ";
*/
return 0;
}
Or, get rid of the manual loop altogether:
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// RL: omitting actual "bad" words to protect the innocent...
const vector <string> bwords { "word1", "word2", "word3" };
string bleepWordIfBad(const string &word)
{
if (std::find(bwords.begin(), bwords.end(), word) != bwords.end())
return "BLEEP";
else
return word;
}
void outputWord(const string &word)
{
cout << " " << bleepWordIfBad(word) << " ";
}
int main()
{
vector <string> words;
string input;
while (cin >> input)
words.push_back(input);
for_each(words.begin(), words.end(), outputWord);
/*
Alternatively:
for_each(words.begin(), words.end(),
[](const string &word) { cout << " " << bleepWordIfBad(word) << " "; }
);
*/
return 0;
}
Or, get rid of the input vector altogether and just filter the user's input as it is being entered:
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// RL: omitting actual "bad" words to protect the innocent...
const vector <string> bwords { "word1", "word2", "word3" };
string bleepWordIfBad(const string &word)
{
if (std::find(bwords.begin(), bwords.end(), word) != bwords.end())
return "BLEEP";
else
return word;
}
int main()
{
string word;
while (cin >> word)
cout << " " << bleepWordIfBad(word) << " ";
return 0;
}

need to create a word matcher in c++

need to create a word matcher which counts how many times a specific word is mentioned in a text file. here is what i have done so far and am not sure what iv done wrong. 1 text file contains a long paragraph the other just contains a few words. I need to compare both text files e.g. the word "and" is in the short text file. need to compare this with the long paragraph and see how many time this words appears and then have a report at the end of the program which displays this.
E.g and - 6tmes, but - 0times, it - 23times.
^^ something like this. not sure how to start making this
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile("text1.txt");
if(!infile)
{
cout << "Error";
}
string words[250];
int counter = 0;
while (!infile.eof() )
{
infile >> words[counter];
counter++;
}
ifstream infile2("banned.txt");
if(!infile2)
{
cout << "Error";
}
string bannedwords[250];
counter = 0;
while (!infile2.eof() )
{
infile2 >> words[counter];
counter++;
}
int eatcount= 0;
int orcount = 0;
int hellocount = 0;
int number;
for(int i=0; i<200; i++)
{
for(int j = 0; j < 8; j++)
{
if ( words[i] == bannedwords[j])
{
cout << words[i] << " ";
if (words[i]=="eat")
{
eatcount++;
}
else if (words[i] == "or")
{
orcount++;
}
else if (words[i]== "hello")
{
hellocount++;
}
}
}
}
cout << endl;
cout<< "eat was found "<<eatcount<<" times";
cout << endl;
cout<< "or was found "<<orcount<<" times";
cout << endl;
cout<< "hello was found "<<hellocount<<" times";
system("pause");
}
Why not use a std::multiset?
ifstream infile("text1.txt");
if(!infile)
{
cout << "Error";
}
std::multiset<string> words;
string tmp;
while (!infile.eof() )
{
infile >> tmp;
words.insert(tmp);
}
Then also use a map for the banned words:
ifstream infile2("banned.txt");
if(!infile2)
{
cout << "Error";
}
std::map<string, int> banned;
string tmp;
while (!infile2.eof() )
{
infile2 >> tmp;
banned.insert(tmp);
}
Then you can use std::multiset::count(string) to find the words without all the extra looping. You would only need one loop to go through your banned words list. e.g:
std::map<string, int>::iterator bannedwordIter = bannedwords.begin();
for( ; bannedwordIter != bannedwords.end(); ++bannedwordIter )
{
bannedwordIter->second = words.count(bannedwordIter->first);
// you could print here as you process, or have another loop that prints it all after you finish
cout << bannedwordIter->first << " - " << bannedwordIter->second << " times." << endl;
}
A minimal way would be to use regular expressions, like so
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;
unsigned countMatches(std::istream &is, std::string const &word)
{
string text;
unsigned count(0);
std::regex const expression(word);
while (getline(is, text)) {
count += distance(sregex_iterator(
text.begin(), text.end(), expression), sregex_iterator());
}
return count;
}
so you just pass it the input stream (in your case an input file stream) and it counts the occurences of the word specified after creating a regular expression that matches that word
int main()
{
ifstream ifs;
ifs.open("example_text_file.txt");
cout << countMatches(ifs, "word_you_want_to_search_for") << endl;
return 0;
}

How to read a file into vector in C++?

I need to read from a .data or .txt file containing a new float number on each line into a vector.
I have searched far and wide and applied numerous different methods but every time I get the same result, of a Main.size() of 0 and an error saying "Vector Subscript out of Range", so evidently the vector is just not reading anything into the file.
Note: the file is both in the folder and also included in the VS project.
Anyway, here's my code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<double> Main;
int count;
string lineData;
double tmp;
ifstream myfile ("test.data", ios::in);
double number;
myfile >> count;
for(int i = 0; i < count; i++) {
myfile >> tmp;
Main.push_back(tmp);
cout << count;
}
cout << "Numbers:\n";
cout << Main.size();
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
cin.get();
return 0;
}
The result I get is always simply:
Numbers:
0
Your loop is wrong:
for (int i=0; i=((Main.size())-1); i++) {
Try this:
for (int i=0; i < Main.size(); i++) {
Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy
int main()
{
std::ifstream is("numbers.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
// print the numbers to stdout
std::cout << "numbers read in:\n";
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
}
although you should check the status of the ifstream for read errors.
Just to expand on juanchopanza's answer a bit...
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
does this:
Create i and set it to 0.
Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
Main[-1] is an out-of-bounds access. Kaboom.
Just a piece of advice.
Instead of writing
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
as suggested above, write a:
for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
cout << *it << '\n';
}
to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)
This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.
1.
In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2.
You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
cout<<"File can not open.\n";
return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
dataFile >> name;
test.push_back(name);
}
dataFile.close();
}
//file name must be of the form filename.yourfileExtension
std::vector<std::string> source;
bool getFileContent(std::string & fileName)
{
if (fileName.substr(fileName.find_last_of(".") + 1) =="yourfileExtension")
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector
if (str.size() > 0)
source.push_back(str);
}
/*for (size_t i = 0; i < source.size(); i++)
{
lexer(source[i], i);
cout << source[i] << endl;
}
*/
//Close The File
in.close();
return true;
}
else
{
std::cerr << ":VIP doe\'s not support this file type" << std::endl;
std::cerr << "supported extensions is filename.yourfileExtension" << endl;
}
}