need help with 2 programs ask the user for the text file name, ask the user the
ID: 666113 • Letter: N
Question
need help with 2 programs
ask the user for the text file name, ask the user the search-string-20 charaters or fewer, read the input file, searching for the search string while reading, count occurrences of text string, close text file, print the searh- stringand the number of occurrences
include: no matches, one match many matches,must be case sensitive
======
write a program to read a text file and count the occurrences of each character of each file, the list must be in order from highest occurrences to lowest, each character must be surrounded with the vertical bars and the character counter must be case sensitive
please help
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char input[200],file[22],str[22];
fstream inputFile;
int count;
cout<<"enter the file name ";
cin>>file;
//Open the file in input mode.
inputFile.open(file, ios::in);
//If the file was successfully opened, continue.
if (inputFile)
{
cout<<"enter the string to be searched inside the file ";
cin>>str;
count=0;
while (inputFile) //While last read operation successful, continue
{
getline(inputFile, input);//Read next line
temp = input;
while(temp=strstr(temp,str))//search for str in input
{
count++; //if found increment the count
temp=temp+len(str);// advance the input pointer
}
}
inputFile.close();//Closes the file
cout<<count<<endl
}
}
2)
#include <iostream>
#include <fstream>
#include <cstring>
#include<vector>
#include<algorithm>
using namespace std;
struct ch
{
int count;
char c;
};
bool compare(const ch &a, const ch &b)
{
return a.count > b.count;
}
int main()
{
char input[200],file[22];
fstream inputFile;
int i,cnt[128]={0};
vector <ch> cnts;
cout<<"enter the file name ";
cin>>file;
//Open the file in input mode.
inputFile.open(file, ios::in);
//If the file was successfully opened, continue.
if (inputFile)
{
while (inputFile) //While last read operation successful, continue
{
getline(inputFile, input);//Read next line
for(i=0;i<strlen(input);i++)
{
cnt[input[i]]++;
}
}
inputFile.close();//Closes the file
for(i=0;i<128;i++)
{
cnts.push_back(ch());
cnts[i].count=cnt[i];
cnts[i].c=i;
}
sort(cnts.begin(),cnts.end(),compare);
for(i=0;i<128;i++)
cout<<"| "<<cnts[i].c<<" | "<<cnts[i].count<<" | ";
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.