Home > front end >  How to modify the characters in a char array
How to modify the characters in a char array

Time:09-21

My intention was to use the command line to read input and store it into an array and modify the characters of the array. If the character is '1', then turn it into '0', vice versa. I successfully store the input into an array, yet failed to modify the characters of the array. If I put 0000000000000000000000000000000(32bits) into my program, the output doesn't change.

#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *a = argv[argc-1];
    char arr[33];

    size_t length = strlen(a);
    for(size_t i=0;i<length;i  ) {
        arr[i]=a[i];
    }
    for(int j=0; j<32;j  ) {
        if(arr[j]=='0') {
            arr[j]='1';
        }
        if(arr[j]=='1') {
            arr[j]='0';
        }
    }
    for(int k=0;k<32;k  ) {
        printf("%c",arr[k]);
    }
}

CodePudding user response:

To copy string you need to copy null character as well.

size_t length = strlen(a);
 14 for(size_t i=0;i<=length;i  ){
 15     arr[i]=a[i];

But you do not need to traverse the string twice

size_t i=0;
while((arr[i]=a[i]));

Your if is wrong. It should be

   if(arr[j]=='0') arr[j]='1';
   else arr[j]='0';

CodePudding user response:

you forget to give an else if condition in this part of the code.

for(int j=0; j<32;j  ) {
        if(arr[j]=='0') {
            arr[j]='1';
        }
        else if(arr[j]=='1') {   //This part should be else if
            arr[j]='0';
        }
}

In your code for the value of 0 it changed to 1. But for another if condition the value changed to 0 again.

  • Related