There is a problem, a text is given at the entrance (program code with comments like /*коммент*/ ). It is necessary to cut out comments from this text and return. Here is my example, but it does not work. How can I fix it?: D

 #define L 300 int main() { char s1[L]; // Входной текст char s2[L]; // Выходной текст int fl = 0; printf("Введите исходный текст (макс %d симв.): \n", L); gets(s1); printf("Начальный текст: \n"); puts(s1); strcpy(s2,""); int i = 0; while(i<strlen(s1)) { if (s1[i] == '/' && s1[i+1] == '*') fl = 1; if (s1[i] == '*' && s1[i+1] == '/') fl = 0; if (fl == 0) { int j = 0; strcat(s2, &s1[j]); j++; } i++; } printf("Выходной текст: \n"); puts(s2); system("pause"); } 
  • What should your program do? delete /**/ or add /**/ ? - E1mir
  • @KryTer_NexT return the specified text (text / * string * / text) without / * string * / - Accami
  • And what will happen if something like char a [] = "foo / *" comes to the input; / * real comment * / - Vladimir Martyanov
  • one
    and still need to prevent the int/**/x; merged into intx; . - VladD
  • @ Vladimir Martiyanov is allowed)) - Accami

1 answer 1

Strange piece, what did you want to do here?

 if (fl == 0) { int j = 0; strcat(s2, &s1[j]); j++; } 

PS

 #include <stdio.h> #include <stdlib.h> #include <string.h> const char CMT_START[] = "/*"; const char CMT_END[] = "*/"; static char *remove_comments( const char *string ) { char *cmt; const char *sptr = string; char *copy = malloc( strlen( string ) + 1 ); if( !copy ) { return NULL; } *copy = 0; while( cmt = strstr( sptr, CMT_START ) ) { strncat( copy, sptr, cmt - sptr ); cmt = strstr( cmt + 1, CMT_END ); if( cmt ) { sptr = cmt + sizeof( CMT_END ) - 1; } else { /* Спорный момент: оставлять в строке незавершённый * комментарий или нет. В данном случае он будет * отброшен. */ return copy; } } if( *sptr ) { strcat( copy, sptr ); } return copy; } int main() { char *s = remove_comments( "123 /* 456 */ 789 /* 098 */ abc /*" ); if( s ) { printf( "%s\n", s ); } free( s ); return !s; } 
  • Well, I thought to make a flag to open a comment and close it. Tobish just write down each element of the first to the second, when we find the comment, we do not write it down, but when it ends we continue, but when I output strcat (s2, & s1 [j]); The text is displayed several times, I can not tell why? - Accami
  • First of all, read how the strcat() function works and understand what it does, then think about the place and you applied it for the intended purpose or not. - PinkTux
  • stupid question, but why the pointer is sent to the strcat () function, and not a copy of the variable? - Accami