Answer to Question #316458 in C++ for Krishna

Question #316458

Write a program in C++ that reads text from the keyboard and stores it in a file named


“File1.txt”.


Also, for each of the specified prototypes given below, write the function definitions.


 void copyselc(ifstream& fp, ofstream& fp1):This function reads the


contents of the file “File1.txt” and copies those lines from the file that begin with


the character „#‟ to the file named “File2.txt”.


 void checksize(ifstream& fp1,ifstream& fp2):This function reads


two files “File1.txt” and “File2.txt” and counts the number of characters in


both the files. If the count of characters in both the files is same, then the function should


print the message “Both Files are of the same size” else it should display


“Size of the files is not same”.


 void dispNumNames(ifstream& fp):Assuming that the file “File2.txt”


may also contain numbers (1 to 5), this function will read the contents from the file and


display the number names for any numbers encountered.

1
Expert's answer
2022-03-23T13:45:13-0400
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


void copyselc(ifstream& fp, ostream& fp1) {
    string line;


    while (getline(fp, line)) {
        if (line[0] == '#') {
            fp1 << line << endl;
        }
    }
}


void checksize(ifstream& fp1, ifstream& fp2) {
    fp1.seekg(0, fp1.end);
    int length1 = fp1.tellg();


    fp2.seekg(0, fp2.end);
    int length2 = fp2.tellg();


    if (length1 == length2) {
        cout << "Both Files are of the same size" << endl;
    }
    else {
        cout << "Size of the files is not same" << endl;
    }
}


void dispNumNames(ifstream& fp) {
    char ch, ch2;


    while (fp.get(ch)) {
        switch (ch) {
            case '1':
                cout << "one" << endl;
                break;
            case '2':
                cout << "two" << endl;
                break;
            case '3':
                cout << "three" << endl;
                break;
            case '4':
                cout << "four" << endl;
                break;
            case '5':
                cout << "five" << endl;
                break;
        }
    }
}


int main() {
    ofstream fout("File1.txt");
    string line;

    while (cin) {
        getline(cin, line);
        fout << line << endl;
    }
    fout.close();

    fout.open("File2.txt");
    ifstream fin1("File1.txt");
    copyselc(fin1, fout);
    fin1.close();
    fout.close();

    fin1.open("File1.txt");
    ifstream fin2("File2.txt");
    checksize(fin1, fin2);
    fin1.close();
    fin2.close();

    fin1.open("File2.txt");
    dispNumNames(fin1);
    fin1.close();

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog