Gets () gets multi-line strings, replaces substrings and removes continuously repeated characters. Only when it is encountered for the first time will it be processed normally, and the following will be invalidated?

  c++, question

It is required to enter a multi-line string, replace’ ch’ with k, and replace a pair of repeated characters such as’ mm’ with’ m’;
The problem with the code is … if you enter two lines, only the second line will be processed and put out.
If you enter a line, the first matching pair of characters in the line will be processed, and the rest will not be processed.

I am very concerned aboutwhile (gets(ch)! =NULL)I’m not very familiar with it. If I read one line at a time, there should not be such a stupid problem according to the principle … I hope the elder who understands it can give me some advice.

Code:

int main(){
 char  ch[80]={0};
 int flag=0;
 
 while (gets(ch)!  =NULL) {
 char *p=ch;
 while (*p) {
 if (*p=='c') {
 flag=1;
 }else if(*p=='h'&&flag==1){
 *(p-1)='k';  //Find' ch' and change to' K'
 while (*p){
 *p=*(p+1);  The letters after //'ch' move forward in sequence
 p++;
 }
 flag=0;
 p--;
 }
 if(*(p-1)) {
 If (*p==*(p-1)) {// check duplicate string pairs
 while (*p){
 *p=*(p+1);  //The letters behind move forward in sequence
 if(*(p+1))
 p++;
 }
 p--;
 }
 }
 p++;
 
 }
 
 }
 puts(ch);

}

See a problem

If(*(p-1)) {// here, if the first character is' c', aren't you crossing the line here?
 if (*p==*(p-1)) {
 while (*p){
 *p=*(p+1);
 if(*(p+1))
 p++;
 }
 p--;
 }

In your program, this is not only one place, but also when you move an array, such as
while(p)p=*(p+1)