简体   繁体   中英

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

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;

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

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.

你应该在第二个字符串second_arr的末尾添加char '\\n'来表示它的结束。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM