user3349993
user3349993

Reputation: 309

Redundant characters in string, c

I'm trying to get selected characters from one string into another. Everything looks okay, except the program keeps adding additional characters to the output. And it seems that it tends to add different number of these "unecessary" characters. Where might the problem be?

int main(void) {
    int i,j=0;
    char string[256];
    char second_arr[256];
    scanf("%255s", string);

    for(i=0;i<256;i++){
        if(string[i]=='('||string[i]=='['||string[i]=='{'){
            second_arr[j]=string[i];
            j++;
        }
    }
    printf("%s", second_arr);
}

Say,

input: (hello)(}[} --->
Output:(([[H

Upvotes: 0

Views: 215

Answers (4)

Carey Gregory
Carey Gregory

Reputation: 6846

Problem 1: You're not testing scanf for failure. It can return EOF, or zero to indicate the input didn't match your format string.

Problem 2: You're copying all 256 chars even if the user entered fewer, which means you're copying junk.

Problem 3: You're not adding a null terminator to second_arr.

Just do this:

if (scanf("%255s", string) != 1)
{
    printf("scanf failed\n");
    return 1;
}

for (i = 0; i < 256 && string[i]; i++) {
    if(string[i]=='('||string[i]=='['||string[i]=='{'){
        second_arr[j]=string[i];
        j++;
    }
}
second_arr[j] = '\0';
printf("%s", second_arr);
return 0;

Upvotes: 2

barak manos
barak manos

Reputation: 30136

Try this:

for (i=0; string[i]!=0; i++) // iterate the input string until the null-character
{
    if (string[i] == '(' || string[i] == '[' || string[i] == '{')
        second_arr[j++] = string[i];
}
second_arr[j] = 0; // set a null-character at the end of the output string

Upvotes: 1

You should add at the end of second string second_arr the char '\n' to indicate its end.

Upvotes: -1

weston
weston

Reputation: 54801

There is nothing to terminate the second string. Add

||string[i]=='\0'

to your conditions. Also break out of the loop when you see that null char, but only after you have copied it.

Upvotes: 0

Related Questions