file handling

i was having a problem with my file handling homework...
this is our homework...
Write a program that outputs its own C++ source file to a file called "WithoutComments.cpp" and to the screen, but omitting any of the comments enclosed in "/* ... */" markers (and omitting the markers themselves). The new program in the file "WithoutComments.cpp" should compile and run in exactly the same way as the program from which it was generated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
main()
{ /*every function should start with an open curly brace to indicate the starting of the func*/
char c; /*declaration of char c*/
ifstream file1; /*connects the ifstream "file1" to a following file.*/
ofstream file2;
file1.open("nyl.cpp");
file2.open("withoutcomments.cpp");
file1.get(c);
while(!file1.eof()){
cout<<c;
file2.put(c);
file1.get(c);
}
file2.close();
file1.close();
return 0;
}


MY PROBLEM IS THAT I CANT FIND ANY BUILT-IN FUNCTIONS THAT COUD OMIT ANY MARKER AND THE STATEMENTS THAT ARE INCLOSED TO IT.....

could you help me.....

nyl
Last edited on
You do not need any standard library functions to do that.

It's simple. On the part of your code where you are copying character by character:

1
2
3
4
5
while(!file1.eof()){
cout<<c;
file2.put(c);
file1.get(c);
}


I would add a flag check before
 
file2.put(c);


A short pseudo-code to help you out. It is best to code this by yourself so you'd understand better.

1
2
3
4
5
6
7
if current character is '/' or '*'{
    if previous character is '/'
        skip all characters until '*' or '\n'
}

if current character is '*' and next character is not '/'
    repeat skip

i got your point.... i think this is stupidity on my part but i have no idea how to make it skip all the characters....
do i need to use loops?
Skipping, in your case, is mainly done by not inserting the character to the ofstream.

Loop would not be a bad idea but you need to take note that you already have a loop:
1
2
3
4
5
while(!file1.eof()){
cout<<c;
file2.put(c);
file1.get(c);
}


A simple way to do skip is to have a flag that will be set if you need to skip.
1
2
3
4
5
6
7
8
9
//pseudo-code

if inside comment
    fskip = true;
else
    fskip = false;

if(!fskip)
    file2.put(c);


You'll need to implement the check to see if the current character is inside a comment.
what is the fskip here? is this a variable?
Yes, it is of bool type.
ahw....
sorry... im not familiar with bool type.....
im juz new with programming...
http://www.cplusplus.com/doc/tutorial/variables.html

Look under "Fundamental data types"
thank you....:)
im just wondering....
do i need to use bool types?
Well, I guess you could use an int instead... I wouldn't recommend it, though. This is exactly what bools are made for, so why not use one?
i just dont know ho to use it
Topic archived. No new replies allowed.