1
  FILE* f;  /// pointer to a File structure
  char cuv[100];
  int i;
  f = fopen("exmp.txt", "a+");  /// open the file and add the registry. the end
  puts("enter words to add to file");
  for (i = 1; i <= 3; i++) {
    gets(cuv);  /// enters the character string
    fprintf(f, "% s", cuv);
  }  /// write
  puts("File contents:");
  rewind(f);               /// goes to the beginning of the file
  fscanf(f, "% s", &cuv);  /// read
  puts(cuv);               /// displaying the string on the screen by adding \ n
  getch();
  fclose(f);
}  /// close the file

I have this program that adds words to the end of the file which works fine but i want it to swap the letter a with the letter b and vice versa

I found a piece of code that does what i want but i cant seem to get it working. If i change something it just breaks the code

for (int a = 0; a < strlen(cuv); a++){
  if (cuv[a] == 'a'){
    cuv[a] = m;
  } else if(cuv[a] == 'b'){
    cuv[a] = c;
  }
}

Is there a simpler way to just swap 2 characters?

  • 1
    Note too that [the `gets()` function is too dangerous to use — ever!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) – Jonathan Leffler May 14 '21 at 05:30
  • The `printf()` format strings `"% s"` should not contain the space. See the POSIX specification of [`fprintf()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html), for example. However, it might just be ignored. The space modifier only applies to signed numeric quantities. – Jonathan Leffler May 14 '21 at 05:32
  • 1
    Could you please show a [mcve]? For example, `nome` is never defined. – Bill Lynch May 14 '21 at 05:34
  • Note that the character swapping code has undefined variables `nome`, `c`, `m`. It doesn't seem to bear any relation to the other code. It isn't clear if you want to overwrite each `a` with `b` and each `b` with `a`, or whether you need to find an `a` and a `b` and then swap those. Since neither `c` nor `m` is initialized in the code you show, it is impossible to know what you're up to. – Jonathan Leffler May 14 '21 at 05:37
  • those are 2 different programs i want them togheter – asultsvqcspm May 14 '21 at 05:39

1 Answers1

0
  1. Make these two into functions.

  2. For the second one, try this inside your function. I assume nome is the word in which you want to swap 'a' and 'b'.

# nome must be defined prior to this
for (int a = 0; a < strlen(nome); a++){
  if (nome[a] == 'a'){
    nome[a] = 'b';
  } else if(nome[a] == 'b'){
    nome[a] = 'a';
  }
}
# nome must be returned at this point

Personally, I would choose any other index variable name than 'a' for this purpose.

Jeter-work
  • 782
  • 7
  • 22