'/*'
This is a
multi-character constant. They're evil. Don't use them except maybe as magic numbers. No, just don't use them. Set your compiler to be as strict as possible so it will complain if you use them.
'*'
This is a
single character. This is what you are reading from the file: one character at a time.
You have the right idea so far, except your character confusion is confusing you.
For example, on line 34, you are checking if
ch ==
'/*'. It won't. Ever.
Here are the character sequences you are interested in when handling comments:
/
/
begins a newline-terminated comment. (Ends with a newline.)
/
*
begins a "*/"-terminated comment. (Ends with the
two character sequence
*
/
.)
/
c (where
c is any other character) does not begin a comment.
So, if you read the first character in a
potential comment sequence (a
/
), then you must check to see if it really is a comment. Otherwise it doesn't matter and you can continue on happily.
Again, I suggest you use a
switch statement to help you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
while (infile.get( ch ))
{
switch (ch)
{
case '/': // Hey, we might be at a comment
infile.get( ch );
switch (ch)
{
case '/': // newline-terminated comment
while ((infile.get( ch )) && (ch != '\n'))
;
break;
case ...
}
break;
case '\"': // Hey, this must begin a string literal! (If you do the next one right.)
...
break;
case '\\': // Hmm, this could be something useful too.
...
break;
default: // Well, nothing interesting was found.
break;
}
}
|
Now, there are still a couple of ways you can take this. Keep in mind that comments
cannot appear inside string literals. Hence:
1 2 3 4 5 6
|
#include <iostream>
int main()
{
std::cout << "// I am not a comment" << std::endl;
return 0;
}
|
Hope this helps.