Hello,
my friend ask me to write simple program that open file and removes all commented lines.
Here's what I made:
This code does what it's supposed to do, but I wonder if this could be written more elegant.Code:#include <iostream> #include <fstream> #include <string> using namespace std; int main () { ifstream infile("Test.txt"); ofstream outfile("Test2.txt"); string str, search_start="/*", search_end = "*/"; string :: size_type siz; bool comment = false;//flag that indicates if line is commented //read line while (getline(infile, str)) { //write line to file if there is no markers /*, */ or line is not commented if (str.find("/*") == string :: npos && str.find("*/") == string :: npos && !comment) { outfile << str << endl; } else //line is commented { comment = true; siz = str.find("*/");//try to find end of comment if (siz != string :: npos) { //close comment part and continu, read next line comment = false; continue; } else { //read lines until end of comment marek is found while (siz != string :: npos) { getline(infile, str); siz = str.find("*/"); comment = false; } } } } return 0; }
i think maybe better solution will be to use temp file, if everything goes OK contents of temp file will overwrite original file. ofcourse error checking should include unfinished comment in order to prevent lose of code if there is mistake in comments.
Tell me what you think and perhaps suggest better solution.
Thanks



LinkBack URL
About LinkBacks



CornedBee