Answer to Question #350970 in C++ for BScInf

Question #350970

Write a program to remove unnecessary blanks from a text file. Your program should read the text file and copy it to another text file, but whenever more than one blank occurs consecutively, only one blank should be copied to the second file. The second file should be identical to the first file, except that all consecutive blanks have been replaced by a single blank.


1
Expert's answer
2022-06-20T08:35:35-0400
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

string readfile(const char* filename);
void writeFile(string content, const char* filename);
string delBlanks(string input);

int main()
{
    string in, out;
    cout << "Enter input filename: ";
    cin >> in;
    string s = delBlanks(readfile(in.c_str()));
    cout << "Enter output filename: ";
    cin >> out;
    writeFile(s, out.c_str());
    return 0;
}


string readfile(const char* filename) {
    ifstream ifs;
    string line, content;
    ifs.open(filename, fstream::in);
    while (ifs.good()) {
        getline(ifs, line);
        content += line + "\n";
    }
    return content;
}

void writeFile(string content, const char* filename) {
    ofstream ofs;
    ofs.open(filename, fstream::out | fstream::trunc);
    ofs << content;
}

string delBlanks(string s) {
    string res;
    while (strlen(s.c_str()) != 0) {
        while (s.substr(0, 1) == " ") {
            s = s.substr(1, strlen(s.c_str()) - 1);
        }
        if (s.find(" ") != string::npos) {
            res += s.substr(0, s.find(" ") + 1);
            s = s.substr(s.find(" ") + 1, strlen(s.c_str()) - (s.find(" ") + 1));
        } else {
            res += s;
            s = "";
        }
    }
    return res;
}

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
APPROVED BY CLIENTS