C++ program with file input and output String Processing Labs Directions: Write
ID: 3750485 • Letter: C
Question
C++ program with file input and output
Explanation / Answer
Hi,
I belive for first two questions input file reading and writing in not required, as per my undersating we need to implement the functions for first two question, anyway I've implemented functions and file reading and writing as well.
For question 1 input formateis: string space character
Ex: testtest t
For question 2 input format is: string1 space string2
Ex: test testing
For Question 3 you have already mentioned input format above.
Pls. find the below code.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string str, char token){
vector<string> vec;
string s = "";
for(int i=0; i<str.size(); i++){
if(str[i]==token){
vec.push_back(s);
s="";
}
else{
s+=str[i];
}
}
if(s.length()>0){
vec.push_back(s);
}
return vec;
}
// Function 1
int countChars(string str, char chr){
int count = 0;
for(int i=0; i<str.length(); i++){
if(str[i]==chr){
count++;
}
}
return count;
}
// Function 2
bool isSubString(string str1, string str2){
size_t flag = str2.find(str1);
if(flag!=string::npos){
return true;
}
else{
return false;
}
}
// Function 3
void wordCount(){
ifstream file("C:\Users\user\Desktop\input3.txt");
ofstream outfile("C:\Users\user\Desktop\output3.txt");
string line;
getline(file, line);
vector<string> token = split(line, ':');
for(int i=0; i<token.size(); i++){
//cout<<token[i]<<" "<<token[i].length()<<endl;
outfile << token[i] <<" "<<token[i].length()<<endl;
}
file.close();
outfile.close();
}
int main(){
ifstream f1("C:\Users\user\Desktop\input1.txt");
ifstream f2("C:\Users\user\Desktop\input2.txt");
ofstream o1("C:\Users\user\Desktop\output1.txt");
ofstream o2("C:\Users\user\Desktop\output2.txt");
// Reading file for case 1
string line1;
getline(f1, line1);
vector<string> token1 = split(line1, ' ');
int output1 = countChars(token1[0], token1[1][0]);
o1<<output1<<endl;
f1.close();
o1.close();
// Reading file for case 2
string line2;
getline(f2, line2);
vector<string> token2 = split(line2, ' ');
bool output2 = isSubString(token2[0], token2[1]);
if(output2){
o2<<"true"<<endl;
}
else{
o2<<"false"<<endl;
}
f2.close();
o2.close();
// Case 3
wordCount();
system("pause");
return 0;
}
Hope this is helpful :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.