0

I am new to C programming, and I am trying to figure out how to put a period in between letters. This is my code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void CreateAcronym(char userPhrase[], char userAcronym[]) {
int i;
int count = 0;

    for (i = 0; i < strlen(userPhrase); ++i) {
        if (i == 0 || userPhrase[i - 1] == ' ') {
            if (isupper(userPhrase[i])) {
                userAcronym[count++] = userPhrase[i];
            }
        }
    }
    userAcronym[count] = '\0';
}

int main() {
   char userPhrase[1000]; 
   char userAcronym[20];
   
   fgets(userPhrase, 1000, stdin);
   CreateAcronym(userPhrase, userAcronym);
   printf("%s\n", userAcronym);

   return 0;
}

Example Input: Institute of Electrical and Electronics Engineers My current Output: IEEE What the output should be: I.E.E.E.

How do I insert the periods in the printf function so it will output to I.E.E.E.?

  • `for (i = 0; i < userPhrase[i]; ++i)` is all that is needed. Use the nul-character (e.g. `0`) to terminate the loop and don't call `strlen(userPhrase)` to scan for the `0` every iteration. (though a good compiler may optimize that for you) Using `void CreateAcronym(char *userPhrase, char *userAcronym)` makes clear the application of [C11 Standard - 6.3.2.1 (p3)](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3) – David C. Rankin Jul 08 '22 at 23:01

1 Answers1

2

Instead of writing userAcronym[count++] = userPhrase[i];, you'd like to add both the character and the period:

userAcronym[count++] = userPhrase[i];
userAcronym[count++] = '.';
lorro
  • 10,687
  • 23
  • 36
  • @user3386109 Reverted that part (could work with `int count = -1;` at start, but that's too confusing). – lorro Jul 08 '22 at 22:16
  • Also we trust the compiler to make i++ as fast as ++i ;) – HEllRZA Jul 08 '22 at 22:25
  • @HEIIRZA not here - in other places, it's impossible for the compiler to not use another temporary (or, from the compiler's perspective, register) if you use postfix and use the value of it. – lorro Jul 08 '22 at 22:26
  • -O3 But you may be right. However readability has a higher value here. – HEllRZA Jul 08 '22 at 22:35
  • Thanks for changing it back to `count++`, which is very nice and clean here. I have *never* heard of a rule discouraging the use of postfix `++`. Postfix `++` and `--` are perfectly fine operators; I wouldn't discourage anyone from using them when they're semantically appropriate — and personally I find they're appropriate a lot of the time! – Steve Summit Jul 08 '22 at 23:32