Counting word occurence in textfile - c++

Here's the code that I based here http://www.thecrazyprogrammer.com/2015/02/c-program-count-occurrence-word-text-file.html. (new in c++)
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
int main()
{
// std::cout << "Hello World!" << std::endl;
// return 0;
ifstream fin("my_data.txt"); //opening text file
int count=0;
char ch[20],c[20];
cout<<"Enter a word to count:";
gets(c);
while(fin)
{
fin>>ch;
if(strcmp(ch,c)==0)
count++;
}
cout<<"Occurrence="<<count<<"n";
fin.close(); //closing file
return 0;
}
Error in Patter Counting
my_data.txt has only 3 "world" in it, but as I run the program, it results to
here's the textfile's content
What could go wrong?

A solution using std::string
int count = 0;
std::string word_to_find, word_inside_file;
std::ifstream fin("my_data.txt");
std::cout << "Enter a word to count:";
std::cin >> word_to_find;
while (fin >> word_inside_file) {
if (word_to_find == word_inside_file )
count++;
}
std::cout << "Occurrence=" << count << "";
If you want to find all occurrences inside other strings as well, as mentioned in the comments, you can do something like this:
...
while (fin >> word_inside_file) {
count += findAllOccurrences(word_to_find, word_inside_file);
}
...
Inside findAllOccurrences(std::string, std::string) you will implement a "find all string occurrences inside another string" algorithm.

If you are new to c++ you shouldn't really use gets. Read about "buffer overflow vulnerability". gets() is more like c-style. You should consider using std::cin.

Related

replacing string based on user input c++

i want to receive an input from user and search a file for that input. when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input. (I'm writing a hospital management app and this is a part of project that patients and edit their document).
i completed 90 percent of the project but i don't know how to replace it. check out following code:
#include <iostream>
#include <stream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in|ios::out);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
Myfile.close();
}
for example my file contains this line ( David , ha , 2002 ) and user wants to change 2002 to 2003
You cannot replace the string directly in the file. You have to:
Write to a temporary file what you read & changed.
Rename the original one (or delete it if you are sure everything went fine).
Rename the temporary file to the original one.
Ideally, the rename part should be done in one step. For instance, you do not want to end up with no file because the original file was deleted but the temporary one was not renamed due to some error - see your OS documentation for this.
Here's an idea:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
void replace(string& s, const string& old_str, const string& new_str)
{
for (size_t off = 0, found_idx = s.find(old_str, off); found_idx != string::npos; off += new_str.length(), found_idx = s.find(old_str, off))
s.replace(found_idx, old_str.length(), new_str);
}
int main()
{
const char* in_fn = "c:/temp/in.txt";
const char* bak_fn = "c:/temp/in.bak";
const char* tmp_fn = "c:/temp/tmp.txt";
const char* out_fn = "c:/temp/out.txt";
string old_str{ "2002" };
string new_str{ "2003" };
// read, rename, write
{
ifstream in{ in_fn };
if (!in)
return -1; // could not open
ofstream tmp{ tmp_fn };
if (!tmp)
return -2; // could not open
string line;
while (getline(in, line))
{
replace(line, old_str, new_str);
tmp << line << endl;
}
} // in & tmp are closed here
// this should be done in one step
{
remove(bak_fn);
rename(in_fn, bak_fn);
remove(out_fn);
rename(tmp_fn, in_fn);
remove(tmp_fn);
}
return 0;
}
One possible way:
Close the file after you read it into "line" variable, then:
std::replace(0, line.length(), "2002", "2003")
Then overwrite the old file.
Note that std::replace is different from string::replace!!
The header is supposed to be <fstream> rather than <stream>
you can't read and write to a file simultaneously so I have closed the file after reading before reopening the file for writing.
instead of updating text inside the file, your line can be updated and then written to file.
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line, line2;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
int index = line.find(word);
if (index != string::npos){
Myfile.close();
Myfile.open("Patientlist.txt", ios::out);
line.replace(index, word.length(), replacement);
Myfile.write(line.data(), line.size());
Myfile.close();
}
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
}

Having an issue passing an array to a Function as only first word is printed c++

I am new to passing values to functions, please guide me what I am doing wrong here, thanks!
The question: Write a C++ program in which, read a c-string sentence
one by one from a file “sentence .txt”. Now your task is to break each
word of sentence into another c-string word, now write that word into
a file “word.txt”. Note : You must create atleast 1 function to
separate the words from sentence, you cannot use strings.
#include <iostream>
#include <fstream>
using namespace std;
char sentence2word(char array[100])
{
ofstream fout2;
fout2.open("word.txt");
fout2 << array << endl;
return array[100];
}
int main()
{
ifstream fin;
fin.open("sentence.txt");
char array[100];
fin >> array;
cout << "Output successful!";
sentence2word(array);
return 0;
system("pause");
}
The following program show how to get started with reading and writing from/into text files in C++. This is just to get you started and in practice i use std::string and std::istringstream to do this but in your note it is written that we cannot use strings so i did not use std::string. The program reads line by line from an input.txt file and write word by word into an output.txt file.
#include <iostream>
#include <fstream>//needed to read/write files
#define MAX_NUMBER_OF_CHARACTERS 500
using namespace std;
//function that writes lines word by word into output.txt
void writeWordByWord(std::ofstream &m_outFile, char (&lineArg)[MAX_NUMBER_OF_CHARACTERS])
{ int i = 0;
while(lineArg[i] != '\0')
{
if(lineArg[i] != ' ')
{m_outFile << lineArg[i];
//std::cout<< lineArg[i]<<" wrote"<<std::endl;
++i;
}
else{
m_outFile << '\n';
++i;
}
}
//m_outFile << '\n';
}
int main()
{
cout << "Hello World" << endl;
char line[MAX_NUMBER_OF_CHARACTERS];
std::ifstream inFile("input.txt");
std::ofstream outFile("output.txt");
while(inFile.getline(line, MAX_NUMBER_OF_CHARACTERS, '\n'))
{
std::cout<<line<<std::endl;
writeWordByWord(outFile, line);
}
inFile.close();
outFile.close();
return 0;
}

Delimit Sentences in C++, after each period

Sorry if I am brief I had a lot of trouble putting this code up here.
I want to basically parse the file "question.txt"
and every time I see a period i want a new line
basically:
hey jim.(new line)
hey tim.(newline)
int main(){
ifstream openQuiz;
openQuiz.open("questions.txt");
string line;
//int count = 0;
//Check for errors
if (openQuiz.fail()) {
cerr << "Error opening file" << endl;
}
//Reading from beginning to ending;
while (!openQuiz.eof()) {
}
openQuiz.close();
return 0;
}
You could use an fstream instead of an ifstream. The difference is that fstreams can do input and output at the same time.
Then you could simply read the characters one by one. Whenever you read a '.' write a newline.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream f("file.txt");
char c;
while (f.get(c)) {
cout << c;
if (c=='.') cout << endl;
}
return 0;
}
How's this for you?
You can read more about std::istream::get() here http://www.cplusplus.com/reference/istream/istream/get/

Iterating Over Words in a Paragraph Line by Line in a file

I a little new to istringstream operations. I need to find a way to iterate over words in a text file containing eight paragraphs. I need to get each words, test for certain conditions, and then store into a linked list if it passes the checklist. All I need help doing is how to extract each word one by one, use it, check it, and so forth. Here is some code I had: Could anyone lend some advice? I have a loop but it doesnt update the value of the string substrings, Thanks
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
string getLineOfText(ifstream &strIn);
string parseLineOfText(string&);
int main()
{
ifstream in("Text.txt");
istringstream strI;
string substrings;
string strg;
int lineCount = 0;
while (!in.eof())
{
strg = getLineOfText(in);
++lineCount;
strI.str(strg);
while (strI >> substrings)
cout << substrings << " ";
strI.str("");
}
cout << substrings << endl;
cout << endl << lineCount << endl;
system("pause");
return 0;
}
string getLineOfText(ifstream &strIn)
{
string lineTxt;
getline(strIn, lineTxt);
return lineTxt;
}
Move the definition of strI inside the outer while loop.
int main()
{
ifstream in("Text.txt");
string strg;
int lineCount = 0;
while (!in.eof())
{
strg = getLineOfText(in);
++lineCount;
istringstream strI(strg);
string substrings;
while (strI >> substrings)
cout << substrings << " ";
}
cout << endl << lineCount << endl;
system("pause");
return 0;
}

Counting the number of words in a file

#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int hmlines(ifstream &a){
int i=0;
string line;
while (getline(a,line)){
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a){
int i=0;
char c;
while ((c=a.get()) && (c!=EOF)){
if(c==' '){
i++;
}
}
return i;
}
int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "give me the name of the file i wish to count lines, words and chars: ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()){
goto start;
}
l = hmlines(matos);
matos.seekg(0, ios::beg);
w = hmwords(matos);
/*c = hmchars(matos);*/
cout << "The # of lines are :" << l << ". The # of words are : " << w ;
matos.close();
}
The file that i am trying to open has the following contents.
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
The output i get is:
give me the name of the file i wish to count lines, words and chars: ert.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
The # of lines are :4. The # of words are : 0
int hmwords(ifstream &a){
int i;
You've forgotten to initialize i. It can contain absolutely anything at that point.
Also note that operator>> on streams skips whitespace by default. Your word counting loop needs the noskipws modifier.
a >> noskipws >> c;
Another problem is that after you call hmlines, matos is at end of stream. You need to reset it if you want to read the file again. Try something like:
l = hmlines(matos);
matos.clear();
matos.seekg(0, ios::beg);
w = hmwords(matos);
(The clear() is necessary, otherwise seekg has no effect.)
Formatted input eats whitespaces. You can just count tokens directly:
int i = 0;
std::string dummy;
// Count words from the standard input, aka "cat myfile | ./myprog"
while (cin >> dummy) ++i;
// Count files from an input stream "a", aka "./myprog myfile"
while (a >> dummy) ++i;