Removing characters inside brackets in C

I created a program that will remove the characters inside the brackets. The text entered must have the corresponding open and closing parentheses.

Case 1:

Input:   (Hello) World
Output:World

Case 2:

Input:   (Hello World
Output:(Hello World

Case 3:

Input:   Hello)(World
Output:Hello)(World

Case 4:

Input:   Hello((hi) World)
Output:Hello

Case 5:

Input:   (Hello) hi (World)
Output:hi

Here is my code:

#include <stdio.h>
int main(){
    char string[100] = {0};
    char removedletters[100] = {0};
    fgets(string, 100, stdin);
    char *p;
    int x = 0;
    int b = 0;
    for (p=string; *p!=0; p++) {
        if (*(p-1) == '(' && x) {
            x = 0;
        }
        if (*p == ')') {
            x = 1;
        }
        if (!x){
            removedletters[b] = *p;
            b++;
        }
    }
    puts(removedletters);
}

Case 1, 3 and 5 are true, but not in cases 2 and 4. What is wrong with my code?

+5
source share
2 answers

You invoke undefined behavior:

for(p=string; *p!=0; p++){
    if(*(p-1) == '(' && x){
        x = 0;
    }

For the first time it p++is evaluated at the end of the block-cycle, therefore for the first time it *(p-1)points to the one to the left of string, i.e. you do *(string-1).

Unfortunately, you lose your warranty if you have undefined behavior.

+2

, , ( , ).

-:

// str is the input string, set up to and from pointers.
stacktype stack = empty-stack
char *from = str
char *to = str

// Process every character once and once only.
while *from != '\0':
    switch *from:
        // Open, transfer character and store position on stack.
        case '(':
            *to++ = *from++
            stack.push (to - 1)
            break

        // Close, get most recent '(' and adjust to for overwrite.
        //   If no most recent, just transfer as is.
        case ')':
            if stack is not empty:
                to = stack.pop()
            else:
                *to++ = *from++
            break

        // Anything else, just transfer.
        default:
            *to++ = *from++

// Terminate string at truncated position.
*to = '\0'

, ( , .

, ), to, (, (...).

+1

All Articles