Home > Enterprise >  I would like to know what's wrong with this tiny code that it doesn't provide the expected
I would like to know what's wrong with this tiny code that it doesn't provide the expected

Time:04-17

In short, the purpose behind this program is to loop through the given array of strings and print it out as is after changing any Comma (,) to Colon(:).

int main(int argc, string argv[])
{
  int i;
  int j;
  int n;
  int x;
  int count = 0;

    for ( i = 1, n = argc -1; i <= n; i  )
  {
    for ( j = 0, x = strlen(argv[i]); j < x; j  )
    {

      if(strcmp(&argv[i][j], ",") == 0)
      {
        //count  ;
        printf(":");
      }

      else {printf("%c", argv[i][j]);}
    }
  }
  printf("\n");
  //printf("Count = %i & i = %i & j= %i\n", count, i, j);
  //printf("x= %i\n",x);
}

Here is the result that I get after running the code:

$ ./conversion 12, 1,2 ,12
12:1,2,12

What I expect is to get this instead:

$ ./conversion 12, 1,2 ,12
12:1:2:12

Conclusion: I believe that for some reason the comma is not recognized in the beginning/middle of the string It works if it is at the end of the text though. I hope you can tell me how to obtain the expected result.

Thanks in advance!

CodePudding user response:

The expression &argv[i][j] is the i-th string from the j-th character on. When you compare that to the comma string, "," it will match only when the comma is at the end of the string. In your example, the comma is found in "12,", but not in "1,2" or ",12".

When you print the characters, you use the expression argv[i][j] without the &, which is the j-th character of the i-th string. Use that when you check for a comma, too:

if (argv[i][j] == ',') // comma found!

Of course, you must check against a character literal in single quotes here. strcmp is useful for comparing null-terminated strings. Individual characters can be compared with normal comparsison operators.

  • Related