C++ to C comment replacement 
Author Message
 C++ to C comment replacement

Has anyone written, or know of someplace where I may find a tool to replace
the C++ comment style // with the ordinary C comment style /* */ ?

Feel free to post & reply
-- Michael D.
**** BITS WANT TO BE FREE
Michael Dereszynski



Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

I don't know about a tool to specifically convert C++ to C comment styles
but I do know a quick way to do it using an editor such as emacs which
supports macros. Basically, record a macro which finds the string "//",
deletes it and inserts "/*" executes the goto end of line command and
inserts "*/". Stick this macro in a repeat count with a large repeat and it

stops when an error condition occurs (e.g. not found). This takes about a
minute to do using emacs.

If you don't have (or can't get hold of) emacs/eve or similar  Word 6 can
do
the same job  so I imagine most modern WP packages can as well.

I hope this is of some use.

Andrew Thornbury
---------------------------------------------------------
I appreciate the suggestion.  Here's the problem, I have about 20
sub-directories of files (anywhere from 10-50 files/directory).  So to load
each of these files by hand is extremely cumbersome.  I was hoping to find
a utility which could recurse subdirectories and do multiple files
(automatically!)



Quote:
> Has anyone written, or know of someplace where I may find a tool to
replace
> the C++ comment style // with the ordinary C comment style /* */ ?

> Feel free to post & reply
> -- Michael D.
> **** BITS WANT TO BE FREE
> Michael Dereszynski




Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

: Has anyone written, or know of someplace where I may find a tool to replace
: the C++ comment style // with the ordinary C comment style /* */ ?

: Feel free to post & reply
: -- Michael D.
: **** BITS WANT TO BE FREE
: Michael Dereszynski

How about plain ol' sed if you want something simple?

% cat comments
// This is a comment
// on two lines.

x = 5; // This is another comment.
% sed 's#//\(.*\)$#/*\1 */#' comments
/* This is a comment */
/* on two lines. */

x = 5; /* This is another comment. */

JcL

--

%%% lay to rest your soul and body / lay beside your name : Natalie    %%%
%%% lay to rest your rage / your hunger and amazing grace : Merchant   %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement


|> Has anyone written, or know of someplace where I may find a tool to replace
|> the C++ comment style // with the ordinary C comment style /* */ ?

I sent Michael one simple solution (in Perl).

It occurs to me, though, thyat this would make a nice C project for
someone who wants practice in string handling/file parsing.

I've got one C solution in the back of my mind (involving strtok
and its string.h buddies)

Anybody else want to try their hand at this, and post what they come up
with?
--
* "And I don't like doing silly things (except on purpose)."



Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

Quote:

>Has anyone written, or know of someplace where I may find a tool to replace
>the C++ comment style // with the ordinary C comment style /* */ ?


I'll send you a couple (one written in C, the other in C++, both free with
source).


Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

-----BEGIN PGP SIGNED MESSAGE-----


Quote:
> % cat comments
> // This is a comment
> // on two lines.

> x = 5; // This is another comment.
> % sed 's#//\(.*\)$#/*\1 */#' comments
> /* This is a comment */
> /* on two lines. */

> x = 5; /* This is another comment. */

Unfortunately, this idea will have a problem with comment characters
embedded in strings, i.e.

foo = "bar//foo";

While this is somewhat silly, the string assigned to foo is
``bar//foo'', not ``bar''.

Unfortunately, with sed there's not a really easy way to get around
this.  If you were using perl, you might try to escape it like this:

s|(".*?)//(.*?")|$1\201$2|g;
s|//(.*)|/* $1 */|;
s|\201|//|g;

But this fails if your source has eight bit characters, or if it looks
like this:

foo = "bar//foo";  // some sort of stupid "OS" thing.

This is not exactly an easy problem, and barring a code walker, the
sed script is probably the best way to go.  Just don't trust it
blindly.
- --

``Never attribute to malice that which is adequately explained by
        stupidity.'' -- Hanlon's Razor
Home page at: http://www.cs.ucsb.edu/~ghughes/

-----BEGIN PGP SIGNATURE-----
Version: 2.6.2
Comment: Processed by Mailcrypt 3.4, an Emacs/PGP interface

iQCVAwUBMiPBFyqNPSINiVE5AQELPwP+OJ1LMRA/tlmuaQsw+6wjLs+YVD83JypW
V3RkWVcedseYg/pjDs22YOCUo6bKoq8LGNBjdeWL9oPOK0GSClmerzRz1BmOkRTW
M8ba+IRpXfqIdWVgOof7O0YY8lLhBalgnwd5rk7g626NZhITvba20UYQwTHKDaag
vv5ds6Bc2mw=
=h/T/
-----END PGP SIGNATURE-----



Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement



Quote:

>: Has anyone written, or know of someplace where I may find a tool to replace
>: the C++ comment style // with the ordinary C comment style /* */ ?

>: Feel free to post & reply
>: -- Michael D.
>: **** BITS WANT TO BE FREE
>: Michael Dereszynski

>How about plain ol' sed if you want something simple?

>% cat comments
>// This is a comment
>// on two lines.

>x = 5; // This is another comment.
>% sed 's#//\(.*\)$#/*\1 */#' comments
>/* This is a comment */
>/* on two lines. */

>x = 5; /* This is another comment. */

This is somewhat like my first answer would have looked like.
Unfortunately, this won't work for one of the most common cases:
somebody using both /* */ comments and // comments.

The catch is that /* */ and // can mix nicely, where usual C comments
don't nest.

A good solution would have to handle stuff like
// c = 5; /* this was another comment */

Or
/* code commented out
   c = 5; // makes c be 5
 */

properly.

This means you have at least to parse both styles of comments.
--
[nosave]<http://www.eleves.ens.fr:8080/home/espie/index.html>
microsoft network is EXPLICITLY forbidden to redistribute this message.
`Seiza no matataki kazoe, uranau koi no yuku e.'



Sat, 13 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

[This is about all I'm going to accept on this thread, and is about as
 far as code is allowed to drift. -mod]

Quote:

>I don't know about a tool to specifically convert C++ to C comment styles
>but I do know a quick way to do it using an editor such as emacs which
>supports macros. Basically, record a macro which finds the string "//",
>deletes it and inserts "/*" executes the goto end of line command and
>inserts "*/".

This is just s://.*$:/* & */:
in ed or sed.  The whole thing is probably a one-liner in PERL.
However, you should be aware that it has some problems:

(1) If // appears in a string or comment it will be trashed.
        char *URL = "http://www.foo.bar.com/~zoo/snark.html";
    will be trashed to
        char *URL = "http:/* www.foo.bar.com/~zoo/snark.html"; */

        /* Here we implement the MATLAB // operator */
    will be trashed to
        /* Here we implement the MATLAB /* operator */ */

(2) If /* appears in a // comment things will go wrong.
        // Delete all files matching the pattern ./*/.core
    will be trashed to
        /* Delete all files matching the pattern ./*/.core */
    which ends too early.

There really is _no_ substitute for a tool which understands C lexing.

Here's a lexer for ANSI C

me from outside HP (via Vick Khera of CMU), and I have sort of fixed it
up to conform to the latest draft of the standard (Dec 88).  I'm not
sure if I missed out on anything.."

You will need to modify it to recognise // comments, which is as easy
as adding a line

"//"  { cpp_comment(); }

and writing a suitable cpp_comment() function that
    - writes /*
    - copies characters to the end of the line,
      inserting a ' ' before and after each '/'
    - writes */

I leave this as an exercise for the reader.

---------------- scan.l ----------------
O                       [0-7]
D                       [0-9]
L                       [a-zA-Z_]
H                       [a-fA-F0-9]
E                       [Ee][+-]?{D}+
FS                      [fFlL]
IS                      ([uU][lL]?|[lL][uU]?)

%{
#include <stdio.h>
#ifndef FILENAME_MAX
#define FILENAME_MAX 1024
#endif
char yyfilename[FILENAME_MAX+1];

#include "scanaux.h"
#include "y.tab.h"

#undef input
extern  int     input   ();
%}

%%

"#"                   { line_number(); }
"/*"                  { comment(); }

"auto"                        { return AUTO; }
"break"                       { return BREAK; }
"case"                        { return CASE; }
"char"                        { return CHAR; }
"const"                       { return CONST; }
"continue"            { return CONTINUE; }
"default"             { return DEFAULT; }
"do"                  { return DO; }
"double"              { return DOUBLE; }
"else"                        { return ELSE; }
"enum"                        { return ENUM; }
"extern"              { return EXTERN; }
"float"                       { return FLOAT; }
"for"                 { return FOR; }
"goto"                        { return GOTO; }
"if"                  { return IF; }
"int"                 { return INT; }
"long"                        { return LONG; }
"register"            { return REGISTER; }
"return"              { return RETURN; }
"short"                       { return SHORT; }
"signed"              { return SIGNED; }
"sizeof"              { return SIZEOF; }
"static"              { return STATIC; }
"struct"              { return STRUCT; }
"switch"              { return SWITCH; }
"typedef"             { return TYPEDEF; }
"union"                       { return UNION; }
"unsigned"            { return UNSIGNED; }
"void"                        { return VOID; }
"volatile"            { return VOLATILE; }
"while"                       { return WHILE; }

{L}({L}|{D})*           { return check_type(); }

0[xX]{H}+{IS}?          { return CONSTANT; /* hexadecimal constant */}
0{O}*{IS}?              { return CONSTANT; /* octal constant */}
[1-9]{D}*{IS}?          { return CONSTANT; /* decimal constant */}

{D}+{E}{FS}?            { return CONSTANT; }
{D}*"."{D}+({E})?{FS}?        { return CONSTANT; }
{D}+"."{D}*({E})?{FS}?        { return CONSTANT; }

'(\\.|[^\\'])+'         { return CONSTANT;              /* L'c' NOT handled */}
\"(\\.|[^\\"])*\"        { return STRING_LITERAL;        /* L"s" NOT handled */}

"..."                   { return ELLIPSIS; }
">>="                   { return RIGHT_ASSIGN; }
"<<="                   { return LEFT_ASSIGN; }
"+="                  { return ADD_ASSIGN; }
"-="                  { return SUB_ASSIGN; }
"*="                  { return MUL_ASSIGN; }
"/="                  { return DIV_ASSIGN; }
"%="                  { return MOD_ASSIGN; }
"&="                      { return AND_ASSIGN; }
"^="                  { return XOR_ASSIGN; }
"|="                  { return OR_ASSIGN; }
">>"                    { return RIGHT_OP; }
"<<"                    { return LEFT_OP; }
"++"                  { return INC_OP; }
"--"                  { return DEC_OP; }
"->"                       { return PTR_OP; }
"&&"                  { return AND_OP; }
"||"                  { return OR_OP; }
"<="                       { return LE_OP; }
">="                       { return GE_OP; }
"=="                  { return EQ_OP; }
"!="                  { return NE_OP; }
";"                   { return ';'; }
"{"                   { return '{'; }
"}"                   { return '}'; }
","                   { return ','; }
":"                   { return ':'; }
"="                   { return '='; }
"("                   { return '('; }
")"                   { return ')'; }
"["                   { return '['; }
"]"                   { return ']'; }
"."                   { return '.'; }
"&"                       { return '&'; }
"!"                   { return '!'; }
"~"                   { return '~'; }
"-"                   { return '-'; }
"+"                   { return '+'; }
"*"                   { return '*'; }
"/"                   { return '/'; }
"%"                   { return '%'; }
"<"                        { return '<'; }
">"                        { return '>'; }
"^"                   { return '^'; }
"|"                   { return '|'; }
"?"                   { return '?'; }

[ \t\v\n\f]             { }
.                       { /* ignore bad characters */ }

%%

int yycolumn = 0;

yywrap()
    {
        return 1;
    }

int inpeek()
    {
        if (yysptr > yysbuf) {
            /* retrieve pushed-back character */
            return yysptr[-1];
        } else {
            int c = getc(yyin);
            if (c == EOF) return 0;
            ungetc(c, yyin);
            return c;
        }
    }

int input()
    {
        if (yysptr > yysbuf) {
            /* retrieve pushed-back character */
            yytchar = *--yysptr;
        } else {
            yytchar = getc(yyin);
            if (yytchar == EOF) return 0;
            if (input_echo) output(yytchar);
        }

        /* count yycolumn and yylineno */
        if (yytchar == '\n') {
            yylineno++;
            yycolumn = 0;
        } else
        if (yytchar == '\t') {
            yycolumn += 8 - yycolumn%8;
        } else {
            yycolumn++;
        }

        return yytchar;
    }

comment()
    {
        int c;
        int oldline = yylineno, oldcol = yycolumn;

        while ((c = input()) != 0 && (c != '*' || inpeek() != '/')) {}
        if (c == 0) {
            fprintf(stderr,
                "Unterminated /*comment began at column %d of line %d\n",
                oldcol, oldline);
            exit(EXIT_FAILURE);
        }
        (void) input();
    }

#define READWHILE(cond) while(cond) c = input();
line_number()
    {
        char c;
        int oldline = yylineno;

        /* skip spaces and tabs */
        do c = input(); while (c == ' ' || c == '\t');

        if (c == 'i' /*ident*/ || c == 'p') {
            do c = input(); while (c != '\n');
            return;
        }

        /* check for a line number */
        if (c >= '0' && c <= '9') {
            int line_num = 0;

            while (c >= '0' && c <= '9') {
                line_num = line_num * 10 + c - '0';
                c = input();
            }
            if (line_num > 0) yylineno = line_num - 1;

            /* skip spaces and tabs */
            while (c == ' ' || c == '\t') c = input();

            /* check for a file name in double quotes */
            if (c == '"') {
                char *yf = yyfilename;

                while ((c = input()) != 0 && c != '"') *yf++ = c;
                *yf = '\0';
                if (c == 0) {
                    fprintf(stderr, "bad directive at line %d\n", oldline);
                    exit(EXIT_FAILURE);
                }

                /* skip any remaining spaces and tabs */
                do c = input(); while (c == ' ' || c == '\t');
            }
        }

        /* The ANSI standard admits no characters after the file name */
        /* GCC stuffs other numbers there, so play safe */
        while (c != '\n') c = input();
    }

int check_type()
    {
        return lookup_tdname(yytext, yyleng) ? TYPE_NAME : IDENTIFIER;
    }

---------------- end of file ----------------

--
Australian citizen since 14 August 1996.  *Now* I can vote the xxxs out!
Richard A. O'Keefe; http://www.cs.rmit.edu.au/~ok; RMIT Comp.Sci.



Sun, 14 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

[snipped suggestion for using emacs macro to fix comments]

|> I appreciate the suggestion.  Here's the problem, I have about 20
|> sub-directories of files (anywhere from 10-50 files/directory).  So to
|> load each of these files by hand is extremely cumbersome.  I was hoping
|> to find a utility which could recurse subdirectories and do multiple
|> files (automatically!)

No problem in emacs.  Simply edit */*.c.  As you close each file
using C-X C-S C-X K, emacs will call up the next file.

--



Sun, 14 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

Quote:

>I don't know about a tool to specifically convert C++ to C comment styles
>but I do know a quick way to do it using an editor such as emacs which
>supports macros. Basically, record a macro which finds the string "//",
>deletes it and inserts "/*" executes the goto end of line command and
>inserts "*/". Stick this macro in a repeat count with a large repeat and it

This fails when the C++-style comment contains an */.

-------------------------------------
Michael A. Quinlan

http://www.primenet.com/~mikeq
"If it doesn't fit, you must acquit!"
-------------------------------------



Sun, 14 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement

Quote:
> % sed 's#//\(.*\)$#/*\1 */#' comments

But think about its unexpected results on:

    // I'd rather use the old-fashioned /*,*/ pair

or

    a = b * c + d;     // example of higher precedence of */ over +-

Steve Zisk



Sun, 14 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement


 >The whole thing is probably a one-liner in PERL.
 >However, you should be aware that it has some problems:
 >
 >(1) If // appears in a string or comment it will be trashed.
 >   char *URL = "http://www.foo.bar.com/~zoo/snark.html";
 >    will be trashed to
 >   char *URL = "http:/* www.foo.bar.com/~zoo/snark.html"; */
 >
 >   /* Here we implement the MATLAB // operator */
 >    will be trashed to
 >   /* Here we implement the MATLAB /* operator */ */
 >
 >(2) If /* appears in a // comment things will go wrong.
 >   // Delete all files matching the pattern ./*/.core
 >    will be trashed to
 >   /* Delete all files matching the pattern ./*/.core */
 >    which ends too early.
 >
 >There really is _no_ substitute for a tool which understands C lexing.

True - the code I offered on this thread earlier has a parsing engine to do
just that. It also includes a stress test C file with all sorts of
pathological comments. In addition to the things you mention, there are
trigraphs and multi-line C++ comments, e.g.

// This is a \
   multi-line \
   C++ comment



Sun, 14 Feb 1999 03:00:00 GMT  
 C++ to C comment replacement


Quote:
>[This is about all I'm going to accept on this thread, and is about as
> far as code is allowed to drift. -mod]

  Don't kill this quite yet, as there IS a C related question at the end.
Thanks. 8-)

Quote:
>This is just s://.*$:/* & */:
>in ed or sed.  The whole thing is probably a one-liner in PERL.
>However, you should be aware that it has some problems:

>(1) If // appears in a string or comment it will be trashed.
>(2) If /* appears in a // comment things will go wrong.

>You will need to modify it to recognise // comments, which is as easy
>as adding a line

>"//"      { cpp_comment(); }

>and writing a suitable cpp_comment() function that
>    - writes /*
>    - copies characters to the end of the line,
>      inserting a ' ' before and after each '/'
>    - writes */

  Not quite as easy.  I've recently came across code where the author had
used C++ style comments in addition to regular C comments.  Your method will
break in the following case:

        /*
        code();
        code();         // this does foo
        morecode();
        yada();
        */

  Some may say that this isn't a problem, because a C++ comment appears in a
C comment, but I would (for this case) at least want the option of fixing
the C++ comment in the C comment.

  Which leads me to another question.  The author of the code above changed
it to:

        /*
        code();
        code();         /* this does foo
        morecode();
        yada();
        */

and claimed this doesn't break ANSI C, since it isn't nested comments.
Technically, it's not, but at least one ANSI C compiler I tested it on (in
ANSI pedantic mode 8-) gave a warning.  Is this form of C comment legal?

  -spc (In any case, I wouldn't accept code like this anyway ... )



Mon, 15 Feb 1999 03:00:00 GMT  
 
 [ 26 post ]  Go to page: [1] [2]

 Relevant Pages 

1. Newbie: separate big .cs file into small .cs files

2. Change C++ comments to C-comments

3. changing C++ comments // to C comments /*

4. changing C++ comments // to C comments /*

5. Converting C++ comments to C comments

6. Need C++ text for non cs major course

7. How to show/call Form2.cs from Form1.cs ?

8. Include code in other Cs files

9. Reuse of cs files, namespace, arch advice pls

10. word - automatic numbering/bold/underline/italics

11. How to Generate .cs file at Runtime

12. newbe/cs student, need help w/ code

 

 
Powered by phpBB® Forum Software