-2

Design and program code that reads C/C++ program file (Text file) and seperate the comments into another file?

I can read from text file but I'm not understanding how to separate comments into another file

#include<iostream>
#include<fstream>

using namespace std;

int main() {

 ifstream myReadFile;
 myReadFile.open("text.txt");
 char output[100];
 if (myReadFile.is_open()) {
 while (!myReadFile.eof()) {


    myReadFile >> output;
    cout<<output;

 }
}
myReadFile.close();
return 0;
}
O.M
  • 9
  • 1
  • 1
    Is this another assignment again? – regulus Nov 16 '13 at 06:06
  • I can read from text file but I'm not understanding how to separate comments into another file #include #include using namespace std; int main() { ifstream myReadFile; myReadFile.open("text.txt"); char output[100]; if (myReadFile.is_open()) { while (!myReadFile.eof()) { myReadFile >> output; cout< – O.M Nov 16 '13 at 06:14
  • 2
    If you have code relevant to your question, put it in the question, not in a comment. – Benjamin Lindley Nov 16 '13 at 06:16
  • `while ( !myReadFile.eof() )` is incorrect. read more about the "EOF anti-pattern" here: http://stackoverflow.com/questions/5431941 and http://drpaulcarter.com/cs/common-c-errors.php#4.2 – Michael Burr Nov 16 '13 at 07:23
  • A couple other suggestions: read the input file character-by-characters instead of token by token, and use a state machine to track whether or not you're currently 'in a comment'. The state that you're currently in will determine which file you should send output to. – Michael Burr Nov 16 '13 at 07:26
  • @MichaelBurr: a finite state machine wouldn't be able to cut it. You need at least a counter to handle sequences like `/ \ newline \ newline \ newline \ newline * * /` (you cannot know when reading the first `/` if it's a start of a comment or not until you also read an arbitrary amount of line continuations). – 6502 Nov 16 '13 at 10:08

1 Answers1

0

You first need to detect the comments. You would generally split the text and make it an array from there on, you will need to set a boolean as a place holder which will tell you when you encounter the closing tag of the comment.

Basically;

use http://www.cplusplus.com/faq/sequences/strings/split/ as a reference and then scan the arrays one by one with the boolean. That way, you will know where the comment tag starts and ends,

boolean incomment =0 ;

while(incomment)
{
  // Construct your string.
}
Hozikimaru
  • 1,144
  • 1
  • 9
  • 20